Java AtomicLong average(Stream stream)

Here you can find the source of average(Stream stream)

Description

Computes the average of Doubles of a stream.

License

Open Source License

Parameter

Parameter Description
stream stream of Doubles

Exception

Parameter Description
UnsupportedOperationException if stream is parallel.

Return

average value

Declaration

public static double average(Stream<Double> stream) 

Method Source Code


//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;
    }
}

Related

  1. add(AtomicLong requested, long n)
  2. add(AtomicLongFieldUpdater updater, T instance, long n)
  3. addAndGet(AtomicLong current, long toAdd)
  4. addstat(Map stat, String key)
  5. compareAndSetIfGreater(final AtomicLong dest, final long tryValue)
  6. createAtomicId()
  7. createId(final Long baseId)
  8. createObjectID()