1

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.

1
  • What did you try? Commented Mar 16, 2020 at 1:23

1 Answer 1

2

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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.