Java8对多个字段排序

2021-03-07 11:28

阅读:610

标签:private   string   enc   The   out   gen   void   sys   ted   

Java8对多个字段排序

创建User对象

public class Users {

    private Long id;
    private String name;
    private String code;
    private Long supId;
    private List usersList;

    public Users() {
    }

    public Users(Long id, String name, String code, Long supId) {
        this.id = id;
        this.name = name;
        this.code = code;
        this.supId = supId;
    }

}

编写测试类

public class Demo01 {
    List usersList = new ArrayList();
    @Before
    public void generateData() {
        usersList.add(new Users(1l, "张三", "20", 0L));
        usersList.add(new Users(2l, "李四1", "22", 1L));
        usersList.add(new Users(4l, "王五1", "20", 2L));
        usersList.add(new Users(3l, "李四2", "20", 1L));
        usersList.add(new Users(6l, "王五3", "22", 2L));
        usersList.add(new Users(5l, "王五2", "21", 2L));
        usersList.add(new Users(7l, "王五4", "23", 2L));
    }

    @Test
    public void demo1() {
        List collect = usersList.stream().sorted(Comparator.comparing(Users::getSupId).thenComparing(Users::getCode)).collect(Collectors.toList());
        for (Users users : collect) {
            System.out.println(users);
        }
    }

}

以上代码含义是:通过supId字段进行排序,如果supId相同则按照code字段排序。结果集:

Users{id=1, name=‘张三‘, code=‘20‘, supId=0}
Users{id=3, name=‘李四2‘, code=‘20‘, supId=1}
Users{id=2, name=‘李四1‘, code=‘22‘, supId=1}
Users{id=4, name=‘王五1‘, code=‘20‘, supId=2}
Users{id=5, name=‘王五2‘, code=‘21‘, supId=2}
Users{id=6, name=‘王五3‘, code=‘22‘, supId=2}
Users{id=7, name=‘王五4‘, code=‘23‘, supId=2}

Java8对多个字段排序

标签:private   string   enc   The   out   gen   void   sys   ted   

原文地址:https://www.cnblogs.com/xianbeier/p/14267410.html


评论


亲,登录后才可以留言!