我有一张 map :Map<Integer, Map<LocalDate, CustomObject>>
我想对内部 map 的每个值执行操作。
我在 map 中的数据示例:
<1, Map<2018-12-01, "A">
<2018-12-02, "A">
<2018-12-03, "A">
<2018-12-04, "A">
<2018-12-05, "A">>
<2, Map<2018-12-01, "B">
<2018-12-02, "B">
<2018-12-03, "B">
<2018-12-04, "B">
<2018-12-05, "B">>
<3, Map<2018-12-01, "C">
<2018-12-02, "C">
<2018-12-03, "C">
<2018-12-04, "C">
<2018-12-05, "C">>
我尝试将 map 的值添加为 map 列表;喜欢:
List<Map<LocalDate, CustomObject>>
但是我无法实现我想执行的操作
我需要的是智能添加所有元素并生成结果 map 。 IE;我需要像 INTO A RESULTANT MAP 这样的东西
2018-12-01 : A+B+C
2018-12-02 : A+B+C
2018-12-03 : A+B+C
最佳答案
您可以使用flatMap
获取所有内部Map 的条目的Stream
,然后根据需要收集它们:
Map<Integer, Map<LocalDate, CustomObject>> input = ...
Map<LocalDate,List<CustomObject>> grouped =
input.values() // Collection<Map<LocalDate, CustomObject>>
.stream() // Stream<Map<LocalDate, CustomObject>>
.flatMap(m -> m.entrySet().stream()) // Stream<Map.Entry<LocalDate, CustomObject>>
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));
关于java - 在 map 列表中分隔每个 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53863688/