Java8 stream sorted排序时包括null

开发过程中对象集合根据某个属性排序是常常遇到的情况,但有时排序会遇到对应属性值为null的情况,会报空指针异常。

查找stream.sorted源码看到有Comparator.nullsFirstComparator.nullsLast方法,使用方法如下:

List list = Lists.newArrayList(new User("Y", "YY"), new User("A", "AA"), new User(null, "CC"));
list.stream().forEach(System.out::println);
System.out.println("------------------------------");

List nList = list.stream().sorted(
    Comparator.comparing(User::getCode, Comparator.nullsFirst(String::compareTo)))
    .collect(Collectors.toList());
nList.stream().forEach(System.out::println);




out:

Y---YY
A---AA
null---CC
------------------------------
null---CC
A---AA
Y---YY
  class User {
    public User(String code, String name) {
      this.code = code;
      this.name = name;
    }

    private String code;
    private String name;

    public String getCode() {
      return code;
    }

    public void setCode(String code) {
      this.code = code;
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    @Override
    public String toString() {
      return code + "---" + name;
    }
  }

 

你可能感兴趣的:(Java)