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?
Since you're only interested in the values of the
Map
, you can just have:using the Stream API itself. This creates a
Stream<Double>
directly from the values of the map, maps that to the primitiveDoubleStream
and returns the sum.Using StreamEx, you could simplify that to:
using
DoubleStreamEx.of
taking directly aCollection<Double>
.If you already have an
EntryStream
, you won't be able to have anything simpler than: