我有一个嵌套映射Map<String, Map<String, List<ObjectA>>>
传递给我,我想将其更改为 type Map<String, Map<String, Set<ObjectA>>>
,在 Java 中使用流最简单的方法是什么?我曾尝试使用 Collectors.groupingBy 但无法正常工作。
问问题
120 次
1 回答
4
最好的方法是您必须遍历外部映射和内部映射中的每个条目,然后将内部映射条目值转换List<ObjectA>
为Set<ObjectA>
Map<String, Map<String, Set<ObjectA>>> resultMap = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, val -> new HashSet<>(val.getValue())))));
注意:如果您正在转换List
,HashSet
那么您将不会保持相同的订单,因此您可以选择LinkedHashSet
继续HashSet
保持订单
Map<String, Map<String, Set<ObjectA>>> resultMap = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, val -> new LinkedHashSet<>(val.getValue())))));
于 2020-04-14T23:37:55.200 回答