【问题标题】:How to convert Map<String, List<String>> to Map<String, String> in Java 8 [duplicate]如何在 Java 8 中将 Map<String, List<String>> 转换为 Map<String, String> [重复]
【发布时间】:2021-03-12 00:39:52
【问题描述】:

例如我有一个 Map:

{
    "North America": ["New York", "Vancouver"], 
    "Europe": ["London", "Paris"]
}

我想将其转换为 Map

{
    "New York": "North America",
    "Vancouver": "North America",
    "London": "Europe", 
    "Paris": "Europe"
}

如何在 Java 8 中使用 stream() 来实现这一点?

【问题讨论】:

  • 请向我们展示您到目前为止所做的尝试以及您坚持的部分。如果您对流完全陌生,那么tutorial 可能会有所帮助
  • 需要小心转换为可能有重复键的东西......使用您的类比,您可能必须将其放入地图“Melbourne”:“Australia”,“Melbourne”:“ England", "Melbourne" : "North America" [爱荷华州、阿肯色州和佛罗里达州中的 3 个]。
  • 我不相信你会单独使用stream() 找到一个优雅的解决方案,因为你需要考虑重复的键/值。迭代地图可能是最好的选择,虽然我可能是错的。
  • @Zephyr Collectors.groupingBy 会自动处理重复项。

标签: java java-8 java-stream


【解决方案1】:

你可以这样做。

数据

Map<String, List<String>> map = Map.of("North America",
        List.of("New York", "Vancouver", "Paris"), "Europe",
        List.of("London", "Paris"));

过程

  • 流式传输entrySet
  • flatMap 列表并映射到数组
  • 然后使用数组的结果构建新地图。
  • 我添加了一个合并功能来处理重复键,以防一个城市位于两个国家/地区。

Map<String, String> result = map.entrySet().stream()
        .flatMap(e -> e.getValue().stream()
                .map(str -> new String[] { str, e.getKey() }))
        .collect(Collectors.toMap(a -> a[0], a -> a[1],
                (countries, country)->countries + ", " + country,
                HashMap::new));

result.entrySet().forEach(System.out::println);

打印

New York=North America
Vancouver=North America
London=Europe
Paris=Europe, North America

您也可以使用Map&lt;String,List&lt;String&gt;&gt; 来处理重复城市,而不是使用字符串连接来处理重复的城市。这就是它的样子。

Map<String, List<String>> result = map.entrySet().stream()
        .flatMap(e -> e.getValue().stream()
                .map(str -> new String[] { str, e.getKey() }))
        .collect(Collectors.groupingBy(a -> a[0],
            Collectors.mapping(a -> a[1], Collectors.toList())));

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2018-09-06
    • 2016-07-21
    相关资源
    最近更新 更多