我想用lambda将List<Map<Integer, List<Object>>>
转换为Map<Integer, List<Object>>
,但我完全迷失了,到目前为止我得到了这个;
public Map<Integer, List<Object>> getMapofList(List<Map<Integer, List<Object>>> listMaps) {
return listMaps
.stream()
.filter(listMap -> listMap //Obtained Map
.entrySet()
.stream()
.filter(integerListEntry -> nonNull(integerListEntry.getValue())) //Check if there is a List<Object> not null
. //Not sure how to continue to finally just return a Map<Integer, List<Object>>
}
任何提示或帮助都会非常感激!
答案 0 :(得分:2)
一个解决方案是:
return listMaps
.stream()
.flatMap(e -> e.entrySet()
.stream())
.filter(e -> e.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
或者如果可以有重复的密钥,那么您可以使用groupingBy
收集器,如下所示:
return listMaps
.stream()
.flatMap(e -> e.entrySet()
.stream())
.filter(e -> e.getValue() != null)
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));