Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sum the double values of a map stream in streamex?

The StreamEx library seems to really help me write Java 8 streams concisely, especially when considering maps (using mapKeyValue, for example, instead of having to unbox the map entries manually).

If I have a stream of entries in a map, in vanilla Java 8 I can sum the values this way:

someMap.entrySet().stream()
    .mapToDouble(Entry::getValue)
    .sum()

and I can do this in StreamEx too, but I expected to see a better way of doing it in StreamEx, though the best I can come up with is:

EntryStream.of(someMap)
    .values()
    .mapToDouble(d -> d)
    .sum();

which is no better.

Is there a better way I'm missing?

like image 867
Graeme Moss Avatar asked Feb 22 '16 15:02

Graeme Moss


1 Answers

Since you're only interested in the values of the Map, you can just have:

double sum = someMap.values().stream().mapToDouble(d -> d).sum();

using the Stream API itself. This creates a Stream<Double> directly from the values of the map, maps that to the primitive DoubleStream and returns the sum.

Using StreamEx, you could simplify that to:

double sum = DoubleStreamEx.of(someMap.values()).sum();

using DoubleStreamEx.of taking directly a Collection<Double>.


If you already have an EntryStream, you won't be able to have anything simpler than:

double sum = entryStream.mapToDouble(Entry::getValue).sum();
like image 173
Tunaki Avatar answered Sep 29 '22 15:09

Tunaki