自定义比较器:
compare中返回负数,认为第一个参数排在前面,返回正数,认为第二个参数排在前面
public static class AgeUpOrder implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
}
使用方式:
Arrays.sort(students, new AgeUpOrder());
也可以用Lambda
TreeMap<Student, String> treeMap = new TreeMap<>( (a, b) -> a.id - b.id );
但如果不想因为TreeMap的性质导致相同id的只存进一个可以这么写
TreeMap<Student, String> treeMap = new TreeMap<>(
(a, b) -> a.id != b.id ? (a.id - b.id) : (a.hashCode() - b.hashCode()));