1

I have a list of maps and I want to add values if the keys are equal. Values also stored as map. As output I want a single map as in example below.

I expect the output of

[
    {user1={service1=10.24, service2=0.11, service3=18.76}}, 
    {user1={service1=200.25, service2=0.05, service4=0.00}}
    {user2={service1=50.25, service4=0.05, service5=0.00}}
]

to be

{
    user1={service1=210.49, service2=0.16, service3=18.76, service4=0.00},
    user2={service1=50.25, service4=0.05, service6=0.00}
}
2
  • What does the declaration of your variable look like? List<Map<String, Map<String, Double>>>? Commented Aug 15, 2019 at 8:12
  • Don’t define a task by a textual output. Commented Aug 15, 2019 at 8:53

1 Answer 1

2

it's a combination of different collectors:

Map<String, Map<String, Double>> map = list.stream()
            .flatMap(m -> m.entrySet().stream())
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.flatMapping(m -> m.getValue().entrySet().stream(),
                    Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Double::sum))));

Example:

List<Map<String, Map<String, Double>>> list = List.of(
         Map.of("user1", Map.of("service1", 10.24, "service2", 0.11, "service3", 18.76)),
         Map.of("user1", Map.of("service1", 200.25, "service2", 0.05, "service3", 0.0)),
         Map.of("user2", Map.of("service1", 50.25, "service2", 0.05, "service3", 0.0))
);

will produce

{
 user1={service2=0.16, service1=210.49, service3=18.76}, 
 user2={service2=0.05, service1=50.25, service3=0.0}
}
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.