Reputation: 209
I got a solution to a problem I've been trying to fix for a long time. Unfortunately, I cannot use the solution since the target java version is Java 8.
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)));
This would return me a Map like: {New York=USA, Chicago=USA, Los Angeles=USA, Toronto=Canada}
Now my question, can I arrive at this result without using Map.entry(...) in Java 8?
Upvotes: 4
Views: 5594
Reputation: 394116
You can use
.map(city -> new AbstractMap.SimpleEntry<>(city, entry.getValue())))
Upvotes: 9