如何将 Map<String, List<List<String>>> 转换为 Map<String, List<String>>

How to Convert a Map<String, List<List<String>>> to Map<String, List<String>>

 Map<String, List<String>> map1 = new HashMap<>();
  Map<String, List<String>> map2 = new HashMap<>();
   map1.put("a", Lists.newArrayList("1","123"));
    map1.put("b", Lists.newArrayList("2","223"));

    map2.put("c", Lists.newArrayList("11","1123"));
    map2.put("a", Lists.newArrayList("22","2223"));
  Map<String, List<List<String>>> collect = Stream.of(map1, map2)
            .flatMap(m -> m.entrySet().stream())
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue,
                            Collectors.toList())
            ));
 System.out.println(collect);

打印:{a=[[1, 123], [22, 2223, 1, 123]], b=[[2, 223]], c=[[11, 1123]]}

如何打印: {a=[22, 2223, 1, 123], b=[2, 223], c=[11, 1123]}

您可以使用一个简单的 for 循环并像这样进行操作。

List<Map<String, List<String>>> source = Arrays.asList(map1, map2);
for (Map<String, List<String>> m : source) {
    for (Map.Entry<String, List<String>> e : m.entrySet()) {
        target.computeIfAbsent(e.getKey(), unused -> new ArrayList<>())
            .addAll(e.getValue());
    }
}

基于流的对应物应该是这样的。

Map<String, List<String>> res = source.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(Map.Entry::getKey,
        Collectors.flatMapping(e -> e.getValue().stream(), Collectors.toList())));

Collectors.flatMapping 从 java9 开始可用。如果您使用 java8,我建议您为 flatMapping 编写自己的自定义收集器并在此处使用。这也会为 Java9 提供更简单的迁移策略。您可能会找到解释 .

我一开始不会创建 List<List<String>>s

Map<String, List<String>> map1 = new HashMap<>();
Map<String, List<String>> map2 = new HashMap<>();
map1.put("a", Lists.newArrayList("1","123"));
map1.put("b", Lists.newArrayList("2","223"));

map2.put("c", Lists.newArrayList("11","1123"));
map2.put("a", Lists.newArrayList("22","2223"));

Map<String, List<String>> collect = Stream.of(map1, map2)
        .flatMap(m -> m.entrySet().stream())
        .collect(Collectors.groupingBy(Map.Entry::getKey,
                 Collectors.flatMapping(e -> e.getValue().stream(), Collectors.toList())));