1、数组排序
Arrays.sort(int[] a)这种形式是对一个数组的所有元素进行排序,并且是按照从小到大的排序。
public static void main(String[] args) {
Integer []arr = {1,2,3,4,5,6};
//升序
Arrays.sort(arr);
for (int x:arr){
System.out.print(x + " ");
}
System.out.println();
//升序
Arrays.sort(arr,new Comparator<Integer>(){
@Override
public int compare(Integer o1,Integer o2){
return o1-o2;
}
});
for(int x:arr){
System.out.print(x + " ");
}
System.out.println();
//升序
Arrays.sort(arr, (o1, o2) -> o1 - o2);
for (int x:arr){
System.out.print(x + " ");
}
System.out.println();
//降序
Arrays.sort(arr,new Comparator<Integer>(){
@Override
public int compare(Integer o1,Integer o2){
return o2-o1;
}
});
for(int x:arr){
System.out.print(x + " ");
}
System.out.println();
//降序
Arrays.sort(arr, (o1, o2) -> o2 - o1);
for (int x:arr){
System.out.print(x + " ");
}
}
o2 - o1 ----> 降序
o1 - o2 ----> 升序
2、集合排序
Collections.sort(List<> arr)对一个集合的所有元素进行排序,并且按照从小到大的顺序
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(4);
list.add(5);
list.add(6);
list.add(3);
list.add(2);
list.add(1);
//升序
Collections.sort(list);
for (int x : list){
System.out.print(x + " ");
}
System.out.println();
//升序
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
//升序
Collections.sort(list, (o1,o2) -> o1 - o2 );
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
//降序
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
//降序
Collections.sort(list, (o1,o2) -> o2 - o1 );
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}