Java 8 - How to get single values out of Map of Lists?

Luca :

I have the following Map Map<List<String>, String> with the following example values:

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

Is it possible to get a Map Map<String, String> and map every element of the value list to it's key? Example:

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

I need it in a stream, that afterwords I can sort.

Gábor Bakos :

Of course it is possible:

 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)));

An example output:

{New York=USA, Montréal=Canada, Chicago=USA, Vancover=Canada, Los Angeles=USA, Toronto=Canada}

First, you have to flatMap on the entrySet's Stream where you can map the keys to a new Stream of entries for example.

As you mentioned you need it as a Stream, so probably you want to stop before collect:

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

(Those entries you can collect to a new Map.)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=4390&siteId=1