集合流的使用之“根据对象字段进行排序”

一、根据对象字段进行排序【代码】

    @Test
    public void wzwStream()
    {
        List<User> list = new ArrayList<>();
        for (int i = 1; i <= 3; i++)
        {
            User user = new User();
            user.setUserId(i);
            user.setCreatedBy(3 - i);
            list.add(user);
        }

        User user = new User();
        user.setUserId(2);
        user.setCreatedBy(2);
        list.add(user);
        User user1 = new User();
        user1.setUserId(2);
        user1.setCreatedBy(3);
        list.add(user1);


        // 按照id升序 并且 按照创建人降序
        List<User> collect = list.stream()
                .sorted(Comparator.comparing(User::getUserId).reversed().thenComparing(User::getCreatedBy).reversed())
                .collect(Collectors.toList());
        System.out.println("collect1 = " + collect.toString());

        // 按照id降序 并且 按照创建人降序
        List<User> collect1 = list.stream()
                .sorted(Comparator.comparing(User::getUserId).thenComparing(User::getCreatedBy).reversed())
                .collect(Collectors.toList());
        System.out.println("collect2 = " + collect1.toString());
  }

 

二、结果图

1.按照id升序 并且 按照创建人降序

 

2.按照id降序 并且 按照创建人降序

 

posted @ 2023-06-30 16:38  骚哥  阅读(45)  评论(0编辑  收藏  举报