朋也的博客 » 首页 » 文章

Java集合排序,字段为空的排在前面

作者:朋也
日期:2020-03-30
类别:java学习笔记 


版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证

需求:如果跟第三方调接口时,拿回来的列表数据中有的字段是空的,这时候是需要人工处理的,怎么让空的(null,”“)字段的数据展示在最前面?

实现:

class Demo {
    Integer id;
    String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Demo(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
}

@Test
public void test3() {
    List<Demo> demos = new ArrayList<>();
    demos.add(new Demo(8, "222"));
    demos.add(new Demo(4, ""));
    demos.add(new Demo(3, "123"));
    demos.add(new Demo(6, ""));
    demos.add(new Demo(1, null));
    demos.add(new Demo(2, ""));
    demos.add(new Demo(5, "333"));
    demos.add(new Demo(7, null));
    demos.sort(Comparator.comparing(Demo::getName, Comparator.nullsFirst(String::compareTo)));
    for (Demo demo : demos) {
        System.out.println("id: " + demo.getId() + " name: " + demo.getName());
    }
}

执行结果:

id: 1 name: null
id: 7 name: null
id: 4 name:
id: 6 name:
id: 2 name: 
id: 3 name: 123
id: 8 name: 222
id: 5 name: 333