Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 584
ayush sanghvi Avatar asked Mar 05 '23 04:03

ayush sanghvi


2 Answers

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.

like image 139
uneq95 Avatar answered Mar 17 '23 01:03

uneq95


You could do it like this:

mapC = mapA.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> mapB.get(e.getValue())));
like image 39
Kartik Avatar answered Mar 17 '23 03:03

Kartik