Person[] personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice")};
//1. 使用静态的比较器,比较的对象不能为null值
Arrays.sort(personArray, Comparator.comparing(Person::getName));
for (Person person : personArray) {
System.out.println(person.getName());
}
System.out.println();
//2. 使用andThen,在第一层比较相同的情况下,使用andThen的比较器, 多次比较
personArray = new Person[]{new Person("Tom","A","Tom" ),new Person("Tom","B","Tom" ),new Person("Jack"),new Person("Alice")};
Arrays.sort(personArray, Comparator.comparing(Person::getName).thenComparing(Person::getFirstName).thenComparing(Person::getLastName));
for (Person person : personArray) {
System.out.println(person.getName()+"-"+person.getFirstName()+"-"+person.getLastName());
}
System.out.println();
//3. 变体格式,指定具体比较的内容
personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice")};
Arrays.sort(personArray, Comparator.comparing(Person::getName, (x,y)->Integer.compare(x.length(), y.length())));
for (Person person : personArray) {
System.out.println(person.getName());
}
System.out.println();
//4.对于可能返回null的情况,使用nullsFirst和nullsLast适配器
personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice"),new Person()};
Arrays.sort(personArray, Comparator.comparing(Person::getName, Comparator.nullsFirst(Comparator.naturalOrder())));
for (Person person : personArray) {
System.out.println(person.getName());
}
System.out.println();
//5. 逆序比较 Comparator.comparing().reversed()
personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice"),new Person()};
Arrays.sort(personArray, Comparator.comparing(Person::getName, Comparator.nullsFirst(Comparator.naturalOrder())).reversed());
for (Person person : personArray) {
System.out.println(person.getName());
}
System.out.println();
博客地址:https://blog.csdn.net/xiang__liu,https://www.cnblogs.com/xiang--liu/