Here you can find the source of average(Stream
Parameter | Description |
---|---|
stream | stream of Doubles |
Parameter | Description |
---|---|
UnsupportedOperationException | if stream is parallel. |
public static double average(Stream<Double> stream)
//package com.java2s; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; public class Main { /**// w w w. ja va2s .c om * Computes the average of Doubles of a stream. If the stream empty, then * 0,0 will be returned. Note that this method cannot be applied to an parallel * stream. * * Unfortunately count() method cannot be invoked againt the stream because * invoking it will exhaust the stream. Similary, there is no way to count * the number of elements against a parallel stream. * * @param stream stream of Doubles * @return average value * @throws UnsupportedOperationException if stream is parallel. */ public static double average(Stream<Double> stream) { if (stream.isParallel()) { throw new UnsupportedOperationException("Parallel stream is not supported"); } AtomicLong al = new AtomicLong(); double sum = stream.reduce(0.0, (x, y) -> { al.incrementAndGet(); return x + y; }); long count = al.get(); if (count == 0) // empty stream return 0.0; return sum / count; } }