Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

DoubleStream — filtering, counting, and averaging

DoubleStream processes primitive double values through a lazy pipeline. Learn stream creation, filtering, and the terminal operations count() and average().

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

static DoubleStream of(double t)
static DoubleStream of(double... values)
DoubleStream filter(DoublePredicate predicate)
long count()
OptionalDouble average()

java.util.stream.DoubleStream is a stream of primitive double values, rather than Double objects as in Stream<Double>. It does not store data: it describes processing. DoubleStream.of(double t) creates a sequential single-element stream, while DoubleStream.of(double... values) creates a sequential, ordered stream of the supplied values.

DoubleStream.filter(DoublePredicate predicate) is a lazy intermediate operation: it retains values matching the condition. The predicate should be stateless and must not modify the source. A terminal operation triggers processing. DoubleStream.count() returns the number of elements as a long; an empty stream produces 0.

DoubleStream.average() is a terminal operation returning the arithmetic mean in an OptionalDouble. An empty stream produces an empty optional, not a zero average. orElse(-1.0) explicitly selects a fallback value. Floating-point calculations can involve rounding; the average can also be NaN.

After a terminal operation, the pipeline is consumed: do not call count() and average() on the same stream. The example creates two separate streams. Filtering retains 2.0, 4.0, 6.0, so the expected results are 3 and 4.0.

Examples

import java.util.OptionalDouble;
import java.util.stream.DoubleStream;

public class Main {
    public static void main(String[] args) {
        long count = DoubleStream.of(1.0, 2.0, 4.0, 6.0)
                .filter(x -> x >= 2.0)
                .count();

        OptionalDouble average = DoubleStream.of(1.0, 2.0, 4.0, 6.0)
                .filter(x -> x >= 2.0)
                .average();

        System.out.println("count=" + count);
        System.out.println("average=" + average.orElse(-1.0));
    }
}

Result

count=3
average=4.0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources