Java 8-如何从列表映射中获取单个值



我有以下MapMap<List<String>, String>,具有以下示例值:

List["Los Angeles", "New York", "Chicago"] -> "USA",
List["Toronto", "Vancover", "Montréal"] -> "Canada"

是否可以获得MapMap<String, String>并将值列表的每个元素映射到其键?示例:

"Los Angeles" -> "USA",
"New York" -> "USA",
"Chicago" -> "USA",
"Toronto" -> "Canada",
...

我需要把它放在一个流中,我可以整理后记。

当然有可能:

Map<List<String>, String> map = new HashMap<>();
map.put(List.of("Los Angeles", "New York", "Chicago"), "USA");
map.put(List.of("Toronto", "Vancover", "Montréal"), "Canada");
Map<String, String> newMap = map.entrySet().stream().flatMap(entry -> entry.getKey().stream().map(city -> Map.entry(city, entry.getValue()))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));

示例输出:

{纽约=美国,蒙特利尔=加拿大,芝加哥=美国,Vancover=加拿大,洛杉矶=美国,多伦多=加拿大}

首先,您必须在entrySetStreamflatMap,在那里您可以map例如新的Stream条目的密钥。

正如你提到的,你需要它作为Stream,所以你可能想在collect:之前停止

map.entrySet().stream()
.flatMap(entry -> entry.getKey().stream()
.map(city -> Map.entry(city, entry.getValue())))

(您可以将这些条目收集到新的Map中。(

最新更新