简单示例
代码示例参考: Java 8 Lambda 和 Comparator 排序
@Data
@AllArgsConstructor
public class Person {
private String name;
private Integer age;
}
Comparator.comparing(),默认按照指定字段升序。
使用reversed()方法,降序
List<Person> list = new ArrayList<>();
list.add(new Person("老王", 20));
list.add(new Person("老李", 10));
list.add(new Person("老徐", 28));
list.add(new Person("老陈", 18));
list.add(new Person("老艾", 31));
list.stream().sorted(Comparator.comparing(Person::getAge)).forEach(System.out::println);
log.info("-----------------------------");
list.stream().sorted(Comparator.comparing(Person::getAge).reversed()).forEach(System.out::println);
输出:
比较字段null值的处理:Comparator.nullsFirst、Comparator.nullsLast
List<Person> list = new ArrayList<>();
list.add(new Person("老王", 20));
list.add(new Person("老李", 10));
list.add(new Person("老徐", 28));
list.add(new Person("老陈", 18));
list.add(new Person("老艾", null));
list.stream().sorted(Comparator.comparing(Person::getAge,Comparator.nullsFirst(Integer::compareTo))).forEach(System.out::println);
log.info("-----------------------------");
list.stream().sorted(Comparator.comparing(Person::getAge,Comparator.nullsFirst(Integer::compareTo)).reversed()).forEach(System.out::println);
输出: