Collections.sort
Collections.sort(listDevs, new Comparator<Developer>() {
@Override
public int compare(Developer o1, Developer o2) {
return o1.getAge() - o2.getAge();
}
});
List接口排序
//lambda
listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());
//lambda, valid, parameter type is optional
listDevs.sort((o1, o2)->o1.getAge()-o2.getAge());
list.sort((a,b)->{return a.getAge().compareTo(b.getAge());});
list.sort(
Comparator.comparing(User::getName)
.thenComparing(User::getAge)
);
Comparator.comparing
是 Java 8 引入的 Comparator
接口的一个静态方法,允许你基于对象的某个属性或计算结果进行排序
数字升序
List<Integer> list = new ArrayList<>(Arrays.asList(1,5,4,3,7));
list.sort((a,b)->a.compareTo(b));
list.sort(Comparator.comparing(a->a));
list.sort((a,b)->a-b);
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
按第一个数字升序再按第二个数字升序
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<int[]> res = new ArrayList<>();
int n = in.nextInt();
while(n -- > 0) {
int l = in.nextInt();
int r = in.nextInt();
res.add(new int[] {l, r});
}
res.sort((a,b) -> {
if(a[0] != b[0])
return Integer.compare(a[0], b[0]);
else
return Integer.compare(a[1], b[1])
});
}
}