ayush sanghvi
ayush sanghvi

Reputation: 43

Join 2 maps Java 8 using streams

I have 2 Maps

Map<A, B> mapA
Map<B, List<C>> mapB

I want to join these maps on the values in mapA & keys in mapB the result should be

Map<A,List<C>> mapC

I am willing to know how can I do it using streams in Java8.

A,B,C for simplicty, all of these are strings in my case.

Upvotes: 4

Views: 225

Answers (2)

uneq95
uneq95

Reputation: 2228

You can iterate over the map and easily construct the new map.

Map<A,List<C>> mapC = new HashMap<>();

mapA.forEach((key,value)->mapC.put(key, mapB.get(value)));

You can use this link, which compares the efficiency of different ways to iterate over the key-value pairs, to select which method you want to use.

Upvotes: 4

Kartik
Kartik

Reputation: 7917

You could do it like this:

mapC = mapA.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> mapB.get(e.getValue())));

Upvotes: 3

Related Questions