• java8->list转map判空,分组


        /**
         * list转map/分组
         * @Author: Mr.li
         * @Date: 2020/9/8
         */
        @Test
        public void demo7() {
            List<User> userList = new ArrayList<User>() {
                {
                    add(new User("付1", "男1", 20));
                    add(new User("付1", "男", 20));
                    add(new User("付2", "男", 21));
                    add(new User("付3", "男", 22));
                    add(new User("付4", "男", 23));
                    add(new User("付5", "男", 24));
                    add(new User(null, "男", 25));
                }
            };
            User user6 = new User("zhangsan", "男", 24);
            userList.add(user6);
            /** list 转map
             * 注意:要是key重复的话 会报错Duplicate key ....
             * key name  都是1
             * 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
             */
            Map<String, Object> compMap = userList.stream().filter(e->e.getName()!=null).collect(Collectors.toMap(User::getName, a -> a.getAge() + "-->" + a.getName(), (k1, k2) -> k1));
            /*for (Object obj : compMap.keySet()) {
                String key = (String) obj;//取到每一个key值
                String value = (String) compMap.get(key);
                System.out.println(key + ":" + value);
            }*/
            compMap.forEach((k,v)->{
                System.out.println(k+":"+v);
            });
    
    
            /**
             * list中以某个属性分组,比如用name分组
             */
            Map<String, List<User>> map = userList.stream().filter(e->e.getName()!=null).collect(Collectors.groupingBy(User::getName));
            System.out.println("Map: "+map);
            System.out.println("User: "+ getUser(user6));
        }
        /**
         * 得到user
         * @Author: Mr.li
         * @Date: 2020/9/8
         */
        public User getUser(User user) {
            return Optional.ofNullable(user)
                    .filter(u -> "zhangsan".equals(u.getName()))
                    .orElseGet(() -> {
                        User user1 = new User();
                        user1.setName("zhangsan");
                        return user1;
                    });
        }

    result:

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    python3(四)list tuple
    python3(三)enc
    python3(二)
    Scala学习
    spark本地开发环境搭建及打包配置
    最常见的 Git 问题和操作清单汇总
    Idea离线安装plugins插件 如Lombok
    springboot httpsession.getAtt....is null
    idea打包报错Cleaning up unclosed ZipFile for archive D:m2commons-beanutilscommons-beanutils1.9.2...
    springboot https证书配置
  • 原文地址:https://www.cnblogs.com/name-lizonglin/p/13632857.html
Copyright © 2020-2023  润新知