/** * 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: