Vishal Ekkaldevi
Vishal Ekkaldevi

Reputation: 47

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

Upvotes: 0

Views: 70

Answers (2)

Thiyagu
Thiyagu

Reputation: 17890

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.

Upvotes: 1

Thiyagu
Thiyagu

Reputation: 17890

Loop through each map and for each map, loop through the values in the keys map and look it up into the current map and insert the result in the mergedMap. At the end of processing a map, add the mergedMap into the resultList.

for(Map<String, String> eachMap: list){
     Map<String, String> mergedMap = new HashMap<>();
     for (String val: keys.values()) {
        mergedMap.put(val, eachMap.get(val));
     }
     resultList.add(mergedMap);
}

System.out.println(resultList);

This assumes the values in the keys map will always be present in each of the maps. If not you have to check if the key is present before adding to the mergedMap (to avoid adding null values).

Upvotes: 1

Related Questions