user1912054
user1912054

Reputation: 21

Merge maps from a list of maps java8

Hello fellow developers, Need your expertise on below problem I have a below incoming list of maps

Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("name", "alex");
m1.put("age", "40");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "alex");
m1.put("state", "Texas");
l1.add(m1);

m1 = new HashMap<String, Object>();
m1.put("name", "alice");
m1.put("age", "35");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "alice");
m1.put("state", "Arizona");
l1.add(m1);

m1 = new HashMap<String, Object>();
m1.put("name", "bob");
m1.put("age", "25");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "bob");
m1.put("state", "Utah");
l1.add(m1);

I want the output list of map as below using java 8 streams-

[{name="alex", age="40", state="Texas"}
{name="alice", age="35", state="Arizona"}
{name="bob", age="25", state="Utah"}]

Appreciate any help here.

Upvotes: 1

Views: 73

Answers (1)

Hadi
Hadi

Reputation: 17299

You can use toMap() collector with merge function.

l1.stream()
   .collect(Collectors.toMap(m -> m.get("name").toString(), Function.identity(),
               (map1, map2) -> { map1.putAll(map2); return map1;})
           )
   .values();

Indeed in this solution, we merge maps based on name key value. so if two maps have the same value for name key then they will merge. since toMap() collector's result is Map<String,Map<String,Object>> here and desire result is Map<String,Object> so we have called values()

Upvotes: 2

Related Questions