Java sorting method sort usage
- 2020-05-30 20:07:55
- OfStack
In this paper, the example of java to share the array, collection sorting method, for your reference, the specific content is as follows
Sort the array:
// Sort the array
public void arraySort(){
int[] arr = {1,4,6,333,8,2};
Arrays.sort(arr);// use java.util.Arrays The object's sort methods
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
Sorting of sets:
// right list 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 Collections the sort methods
for(int a :list){
System.out.println(a);
}
}
// right list 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 Collections the sort Method, and override compare methods
for(int a :list){
System.out.println(a);
}
}
Note: Collections's sort method defaults to an ascending order, and if you want a descending order, you need to override the conpare method