9

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?

Graeme Moss
  • 7,995
  • 4
  • 29
  • 42
  • 1
    Your solutions are not that bad. I really see no reason to add all the possible shortcuts like `.mapValuesToDouble`, etc. Sometimes it's better to force users to make two calls instead of adding quadratic number of shortcuts (number of possible first calls * number of possible second calls). – Tagir Valeev Feb 22 '16 at 16:38

1 Answers1

9

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();
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • Understood, thanks. However I already have an EntryStream and want to do something with that. I do not have the source of the entry stream. – Graeme Moss Feb 22 '16 at 16:03
  • 2
    @GraemeMoss I see. Well then what you have in your question is really the most simple way then. I edited with that. – Tunaki Feb 22 '16 at 16:29
  • 2
    @Tunaki, agreed. I even see no possibility to add some new feature to make this simpler. – Tagir Valeev Feb 22 '16 at 16:40