list转map

1. List 转 Map

Map> subLineInfoMap = userInfos .stream().collect(Collectors.groupingBy(User::getSex));

2. List 转 Map

MapuserMap = userInfos.stream().collect(Collectors.toMap(User::getStuNum,Function.identity()));

3. List 转 Map

Map collect = userInfos.stream().collect(Collectors.toMap(User::geUserNum, User::getUserName));

4. list 转 map 保持顺序

LinkedHashMap userMap = users.stream().collect(LinkedHashMap::new, (map, item) -> map.put(item.getAccountId(), item), Map::putAll);

5. 将list转成map 并排序

将list 排序,并按照排序后的结果进行有序分组

LinkedHashMap> alarmMap = alarmDataList.stream().sorted(Comparator.comparing(t->t.getId().getData_time())).collect(Collectors.groupingBy(t->t.getId().getVirtualPointId(), LinkedHashMap::new, Collectors.toList()));

将map排序,并且每个key对应的list里面也是排序好的

6. 我们在利用Lambda 将list转成Map时就会出现 Duplicate key xxxx 的异常,意思就是对要转为map的key有重复了,除了进行for循环去重之外,我们还有其它方式能够优雅的处理它.

key重复时直接用后面的值(使用最新的或最老的值)

Map collect = list.stream().collect(Collectors.toMap(User::getExternalUserId, User::getUserId, (val1, val2) -> val2));

将两个值拼接起来

Map collect = list.stream().collect(Collectors.toMap(User::getExternalUserId, User::getUserId, (val1, val2) -> val1+val2));

将重复key的value变成一个集合,注意null值处理

Map> tagMap = list.stream().collect(Collectors.toMap(User::getExternalUserId, s -> { List tags = new ArrayList<>(); tags.add(s.getFollowTags()); return tags; }, (List val1, List val2) -> { val1.addAll(val2); return val1; } ));

你可能感兴趣的:(windows,microsoft)