Forgot where the down note came from. . .
Detailed explanation of the use of the Java sorting method sort
Sort an array:
1 2 3 4 5 6 7 8 |
// sort the array public void arraySort(){ int[] arr = {1,4,6,333,8,2}; Arrays.sort(arr);// Use the sort method of the java.util.Arrays object for(int i=0;i<arr.length;i++){ System.out.println(arr[i]); } } |
Sort the collection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// sort the list in ascending order public void listSort1(){ List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(55); list.add(9); list.add(0); list.add(2); Collections.sort(list);// Use the sort method of Collections for(int a :list){ System.out.println(a); } } // sort the list in descending order public void listSort2(){ List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(55); list.add(9); list.add(0); list.add(2); Collections.sort(list, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; } });// Use the sort method of Collections and override the compare method for(int a :list){ System.out.println(a); } }<br> Note: The default sorting method of Collections is ascending order. If you need to sort in descending order, you need to override the compare method. |