List集合按照某个字段或者属性分组的两种方式

2022-11-28 16:20:30 浏览数 (1)

Java8之前的分组

代码如下:

代码语言:javascript复制
    public static List<User> getUserList(){
        List<User> userList = new ArrayList<>();
        userList.add(new User("小明",11,"北京",66));
        userList.add(new User("小红",12,"上海",99));
        userList.add(new User("小詹",14,"杭州",77));
        userList.add(new User("小龙",16,"伦敦",55));
        userList.add(new User("小斯",9,"杭州",33));
        userList.add(new User("小詹",9,"上海",33));
        userList.add(new User("小布",12,"伦敦",88));
        userList.add(new User("小布",12,"上海",55));
        return userList;
    }

    /**
     * java8之前对象集合根据某个字段分组
     */
    @Test
    public void sortUserListByAge(){
        List<User> userList = getUserList();
        Map<String, List<User>> groupByUserCityMap = new HashMap<>();
        for (User user : userList) {
            List<User> tmpList = groupByUserCityMap.get(user.getCity());
            if (tmpList == null) {
                tmpList = new ArrayList<>();
                tmpList.add(user);
                groupByUserCityMap.put(user.getCity(), tmpList);
            } else {
                tmpList.add(user);
            }
        }
        System.out.println("按照城市分组后结果:" groupByUserCityMap);
    }

输出如下:

代码语言:javascript复制
按照城市分组后结果:{上海=[User(name=小红, age=12, city=上海, score=99), 
User(name=小詹, age=9, city=上海, score=33), User(name=小布, age=12, city=上海, score=55)],
 伦敦=[User(name=小龙, age=16, city=伦敦, score=55), User(name=小布, age=12, city=伦敦, score=88)], 
 杭州=[User(name=小詹, age=14, city=杭州, score=77), User(name=小斯, age=9, city=杭州, score=33)], 
 北京=[User(name=小明, age=11, city=北京, score=66)]}

Java8的分组

代码如下:

代码语言:javascript复制
    /**
     * java8根据某个字段分组
     */
    @Test
    public void java8GroupUserList(){
        List<User> userList = getUserList();
        Map<String, List<User>> groupByUserNameMap = userList.stream().collect(Collectors.groupingBy(User::getName));
        System.out.println("按照姓名分组后结果:" groupByUserNameMap);
    }

输出如下:

代码语言:javascript复制
按照姓名分组后结果:{小龙=[User(name=小龙, age=16, city=伦敦, score=55)], 
小詹=[User(name=小詹, age=14, city=杭州, score=77), User(name=小詹, age=9, city=上海, score=33)], 
小明=[User(name=小明, age=11, city=北京, score=66)], 
小红=[User(name=小红, age=12, city=上海, score=99)], 
小斯=[User(name=小斯, age=9, city=杭州, score=33)], 
小布=[User(name=小布, age=12, city=伦敦, score=88), User(name=小布, age=12, city=上海, score=55)]}

0 人点赞