Java 8 stream sum and count at once

du-*_*-it 0 java average java-stream

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.

Era*_*ran 5

将您的转换StreamDoubleStream并调用average()以计算平均值:

OptionalDouble average = yourStream.mapToDouble(YourStreamElementClass::getFloatValue).average();
Run Code Online (Sandbox Code Playgroud)

如果您需要其他统计信息(例如最大值,最小值,元素数等),则可以调用summaryStatistics()而不是average()