4

我有一个嵌套映射Map<String, Map<String, List<ObjectA>>>传递给我,我想将其更改为 type Map<String, Map<String, Set<ObjectA>>>,在 Java 中使用流最简单的方法是什么?我曾尝试使用 Collectors.groupingBy 但无法正常工作。

4

1 回答 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())))));

注意:如果您正在转换ListHashSet那么您将不会保持相同的订单,因此您可以选择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 回答