Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge maps and make values as array

public class MapCheck {
    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("John", "Taxi Driver");
        data.put("Mark", "Professional Killer");
        Map<String, String> data1 = new HashMap<String, String>();
        data1.put("John", "Driver");
        data1.put("Mark", "Murderer");
        Map<String, String> data3 = new HashMap<String, String>();
        data3.putAll(data);
        data3.putAll(data1);
        System.out.println(data3);
    }
}

I have few maps which contains same key, their values are different. I want to merge them. But when I merge them with the usual putAll() it gives me only the value of the key which was inserted latest.

Output from above code is {John=Driver, Mark=Murderer}

Is there a method which will get me all the values associated with the key and give me as a array like

{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}
like image 520
Melvin Richard Avatar asked Sep 07 '25 11:09

Melvin Richard


1 Answers

You can produce a Map<String, List<String>> quite easily with Java 8 Streams:

Map<String, List<String>>
    merged =
        Stream.of(data,data1) // create a Stream<Map<String,String> of all Maps
              .flatMap(map->map.entrySet().stream()) // map all the entries of all the
                                                     // Maps into a 
                                                     // Stream<Map.Entry<String,String>>
              .collect(Collectors.groupingBy(Map.Entry::getKey, // group entries by key
                                             Collectors.mapping(Map.Entry::getValue,
                                                                Collectors.toList())));

The output Map:

{John=[Taxi Driver, Driver], Mark=[Professional Killer, Murderer]}
like image 147
Eran Avatar answered Sep 09 '25 16:09

Eran