javacollectionsjava-stream

Create a merged map with list of maps


I'm new to java so seeking help from experts. any help would be much appreciated, and a scope for me to learn new things.

I want to create a List of maps(resultList) from a another list of maps(list) where a single map(keys) contains values which are keys to the list of maps(map1, map2, map3 ... So on). Like below example

Map<String, String> keys = new HashMap<>();
keys.put("Animal","Cow");
keys.put("Bird","Eagle");

Map<String, String> map1 =new HashMap<>();
map1.put("Cow","Legs");
m1.put("Eagle","Wings");

Map<String, String> map2 = new HasMap<>();
map2.put("Cow","Grass");
map2.put("Eagle","Flesh");

List<Map<String, String>> list= new ArrayList<>();
list.add(map1);
list.add(map2); // there could be more

List<Map<String, String>> resultList= new ArrayList<>();
for(Map<String, String> eachMap: listOfMaps){
     Map<String, String> mergedMap = new HasMap<>();
     //help me here
}

Now I want values of first map(keys) as key to each new map(mergedMap) for the values of second map(map1) and third map(map2) and so on.

Required output should be like

{ Cow : Legs, Eagle : Wings }
{ Cow : Grass, Eagle : Flesh }
//more

Solution

  • Another way to do it using streams.

    Collection<String> vals = keys.values();
    resultList = list.stream()
        .map(eachMap -> vals.stream()
                .filter(eachMap::containsKey)
                .collect(Collectors.toMap(Function.identity(), eachMap::get)))
         .collect(Collectors.toList());
     
    System.out.println(resultList);
    

    Note: The filter checks if the value is present in the map before creating the map.