0

How can I use Java 8 streams to calculate an average of the stream elements? Because I cannot use a stream twice I have to do it in one iteration. The stream contains custom beans holding a float value. The number of elements in the stream may vary. Hence, I want to sum up the float value of all elements in the stream and divide it by the number of elements in the stream.

Update: Finally I need the sum of all elements in the stream as well a the average of all elemnts of the stream.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
du-it
  • 2,561
  • 8
  • 42
  • 80
  • 1) `reduce` is a general method of iteration, it can do anything a loop can do. In particular, the accumulator can be as complex as you want it to be. For example, you could use an accumulator with is a pair of `(index, sum)` and in the end just divide `sum` by `index`. 2) Actually, average can be computed online without having to know the size of the stream and in fact even for infinite streams: the average at each point of the computation is "new average = old average + (next data - old average) / next count". – Jörg W Mittag Sep 02 '19 at 13:34

1 Answers1

5

Convert your Stream to a DoubleStream and call average() to calculate the average:

OptionalDouble average = yourStream.mapToDouble(YourStreamElementClass::getFloatValue).average();

If you want additional statistics (such as max value, min value, number of elements, etc...), you can call summaryStatistics() instead of average().

Eran
  • 387,369
  • 54
  • 702
  • 768