slakomy
slakomy

Reputation: 333

How to convert map with List as key to collection of merged list values?

I have a structure that looks like this:

Map<Long, List<Double>

I want to convert it to

List<Double>

where each item in this resulting list represents sum of the values for one key. With example Map:

{1: [2.0, 3.0, 4.0],
 2: [1.5, 10.0]}

I want to achieve as a result:

[9.0, 11.5]

or

[11.5, 9.0]

(order doesn't matter). Is it possible with Java 8 merge() method? Actually the case above is a little bit simplified, because in fact my List is parametrized with some complex class and I want to create merged object of this class but I just want to grasp the general idea here.

Upvotes: 2

Views: 118

Answers (1)

Jean Logeart
Jean Logeart

Reputation: 53869

Try:

Map<Long, List<Double>> map = // ...
List<Double> sums = map.values()
                       .stream()
                       .map(l -> l.stream().mapToDouble(d -> d).sum())
                       .collect(Collectors.toList())

Upvotes: 5

Related Questions