zoukankan      html  css  js  c++  java
  • Java8:按照对象的属性,对List集合分组

    一.对象类

    @Data
    @AllArgsConstructor
    public class User {
        private Integer age;
        private String name;
    }
    

     二.普通写法

        private List<User> users =Arrays.asList(new User(20,"张三"),new User(18,"李四"),new User(20,"王五"));
    
        @Test
        public void testGroup(){
            Map<Integer,List<User>>  userMap =  new HashMap<>();
            users.forEach(user->{
                List<User> users = userMap.get(user.getAge());
                if(users==null){
                    users = new ArrayList<>();
                    users.add(user);
                    userMap.put(user.getAge(),users);
                }else{
                    users.add(user);
                }
            });
            userMap.forEach((x,y)->{
                System.out.println(x+":"+y);
            });
        }
    

     三.java8 stream写法:

        @Test
        public void testGroup2(){
            Map<Integer,List<User>>  userMap =  new HashMap<>();
            users.stream().collect(Collectors.groupingBy(User::getAge,Collectors.toList()))
                    .forEach(userMap::put);
            userMap.forEach((x,y)->{
                System.out.println(x+":"+y);
            });
        }
    

    运行结果:

  • 相关阅读:
    1001.A+B Format(20)
    大一下学期的自我目标
    re模块3
    re模块2
    re模块
    configParser模块
    logging模块
    hashlib模块
    sys模块
    isinstance函数
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/13246031.html
Copyright © 2011-2022 走看看