二维数组
- 例1:arr[][] 按照0号元素进行升序(相同时,顺序不改变)
int[][] arr = new int[][]{{1,2},{8,2},{3,2},{5,1},{5,3}};
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] t1, int[] t2) {
return t1[0] -t2[0];
}
});
Arrays.sort(arr, (t1, t2) -> t1[0] -t2[0]);
Arrays.sort(arr, Comparator.comparingInt(t -> t[0]));
- 例2:arr[][] 按照0号元素进行降序(相同时,顺序不改变)
int[][] arr = new int[][]{{1,2},{8,2},{3,2},{5,1},{5,3}};
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] t1, int[] t2) {
return t2[0] -t1[0];
}
});
Arrays.sort(arr, (t1, t2) -> t2[0] -t1[0]);
- 例3: arr[][] 按照0号元素进行降序,然后按照1号元素进行升序
int[][] arr = new int[][]{{1,2},{8,2},{3,2},{5,1},{5,0}};
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] t1, int[] t2) {
if (t1[0] == t2[0]) {
return t1[1] - t2[1];
} else {
return t2[0] -t1[0];
}
}
});
Arrays.sort(arr, (t1, t2) -> {
if (t1[0] == t2[0]) {
return t1[1] - t2[1];
} else {
return t2[0] -t1[0];
}
});
List排序
- Collections.sort(集合,实现了Comparator接口的类的实例化对象)
Collections.sort(students, new Comparator<Students>() {
@Override
public int compare(Students o1, Students o2) {
if (o1.getScore() > o2.getScore()) {
return 1;
} else {
return -1;
}
}
});
- 在自定义类Student里面实现Comparable接口
并重写抽象方法compareTo(Student o)
调用:Collections.sort(集合);
public static class User implements Comparable<User> {
private int score;
private int age;
@Override
public int compareTo(User o) {
if (this.score > o.getScore()) {
return 1;
} else {
return -1;
}
}
}