Luca
Luca

Reputation: 209

Java 8 alternative to Map.entry() for mapping values to new Map?

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

Answers (1)

Eran
Eran

Reputation: 394116

You can use

.map(city -> new AbstractMap.SimpleEntry<>(city, entry.getValue())))

Upvotes: 9

Related Questions