[想要保证顺序](https://blog.csdn.net/qq_43599835/article/details/90339813):
方案:
Map<String, List<GeneralVO>> groupMap2 =
generalVOS.stream().collect(Collectors.groupingBy(GeneralVO::getTaskId,LinkedHashMap::new,Collectors.toList()));
多层次分组:(应该有更好的方法呢todo)
LinkedHashMap<String, List<GeneralVO>> groupMapByStage =
generalVOS.stream().collect(Collectors.groupingBy(GeneralVO::getStageId,LinkedHashMap::new,Collectors.toList()));
LinkedHashMap<String, LinkedHashMap<String, List<GeneralVO>>> groupMapGroupByStageAndTask =new LinkedHashMap<>();
groupMapByStage.forEach((k, v) ->
groupMapGroupByStageAndTask.put(k
, v.stream().collect(Collectors.groupingBy(GeneralVO::getTaskId, LinkedHashMap::new, Collectors.toList()))));
System.out.println(JSON.toJSONString(groupMapGroupByStageAndTask));
如下方
案的不能保证顺序:
方案零:
Map<String, List<GeneralVO>> groupMap =
generalVOS.stream().collect(Collectors.groupingBy(GeneralVO::getTaskId)); //默认hashMap无序
方案一:
Collectors.toMap:
List<String> list = Lists.newArrayList("1", "2", "3", "1");
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(key -> key,
value -> Lists.newArrayList(value),
(List<String> newValueList, List<String> oldValueList) -> {
oldValueList.addAll(newValueList);
return oldValueList;
}));
System.out.println(JSON.toJSONString(map));
即:
Map<String,List<Parts>> partsMap = partList.stream().collect(Collectors.toMap(Parts::getMaintainCode, part ->
Lists.newArrayList(part),(List<Parts> newValueList,List<Parts> oldValueList)->
{oldValueList.addAll(newValueList);
return oldValueList;
}));
更多: [Java8 中 List 转 Map(Collectors.toMap) 使用技巧](https://zhangzw.com/posts/20191205.html)
更多 [ibm stream](https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/)
方案二:
map.merge实现list to map //todo
Java8 list to Map (key 重复 value合并到Collection)
最新推荐文章于 2024-07-18 17:24:13 发布