一维数组
默认升序
int[] people = new int[]{4, 6, 8, 0, 5, 9, 7, 2, 1, 3};
Arrays.sort(people); //默认升序
//输出结果
for (int i = 0; i < people.length; i++) {
System.out.print(people[i] + " ");
}
降序:两种方法,注意这里都要把int类型装箱成Integer才能排序
int[] _people = new int[]{4, 6, 8, 0, 5, 9, 7, 2, 1, 3};
//注意这里只能把int类型装箱成Integer才能排序
Integer[] people = Arrays.stream(_people).boxed().toArray(Integer[]::new);
//方法一:使用Collections.reverseOrder()
Arrays.sort(people, Collections.reverseOrder());
//方法二:重写Comparator
Arrays.sort(people, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
//输出结果
for (int i = 0; i < people.length; i++) {
System.out.print(people[i] + " ");
}
二维数组
已知:
int[][] people = {{7,0},{4,4},{6,1},{5,0},{7,1},{5,2}};
写法一:表示仅根据第二列排序(默认升序),相同时按原顺序,这种写法无法实现降序
Arrays.sort(people, Comparator.comparingInt(o -> o[1])); //按第二列升序
Arrays.sort(people, Comparator.comparingInt(o -> -o[1])); //按第二列降序
另外,使用 lambda 表示式创建 Comparator 会导致算法运行时间过长,也可以如下
Arrays.sort(people, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
写法二:这种写法可以控制两段排序,更加灵活些,如下面的代码,实现先第二列升序,相同时按第一列降序
Arrays.sort(people, (a,b) -> (a[1]==b[1] ? b[0] - a[0] : a[1] - b[1]));
同样,不用lamda表达式,表示为
Arrays.sort(people, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
if(a[1]==b[1]){
return b[0] - a[0];
}else {
return a[1] - b[1];
}
}
});