Java DoubleStream Examples
DoubleStream is the primitive specialisation of Stream for double values, in java.util.stream since Java 8. It is used for measurements, percentages, ratios, scientific values and averages, anywhere fractional numbers appear.
This tutorial shows practical DoubleStream tasks and the floating-point behaviour you must understand to use it safely: rounding, NaN, compensated summation and why money needs a different type.
1. Key DoubleStream Methods
// java.util.stream.DoubleStream (Java 8 unless noted)
static DoubleStream of(double... values)
static DoubleStream iterate(double seed, DoublePredicate hasNext, DoubleUnaryOperator next) // Java 9
double sum() OptionalDouble average() OptionalDouble max() OptionalDouble min()
DoubleStream map(DoubleUnaryOperator f) DoubleStream filter(DoublePredicate p)
<U> Stream<U> mapToObj(DoubleFunction<U> f) Stream<Double> boxed()
DoubleSummaryStatistics summaryStatistics()
There is no range() on DoubleStream; build fractional steps with iterate() or by mapping an IntStream, for example IntStream.rangeClosed(0, 10).mapToDouble(i -> i * 0.1).
2. How DoubleStream Works
A DoubleStream behaves like the other primitive streams. Its sum() and average() use compensated (Kahan) summation, which reduces the rounding error that builds up when many small fractions are added. Results can still differ in the last digits from a simple loop, and between sequential and parallel runs.
double follows IEEE 754 arithmetic: many decimal fractions, such as 0.1, have no exact binary representation; division by zero gives Infinity; and invalid operations give NaN, which spreads through sums and averages.
double values. average() returns an OptionalDouble because the filter may leave nothing.3. DoubleStream Examples
Example 1: Converting and averaging measurements
Convert hourly temperatures from Celsius to Fahrenheit and average the hot readings.
import java.util.stream.DoubleStream;
public class HeatAverage {
public static void main(String[] args) {
double[] celsius = {31.5, 36.2, 38.0, 29.4, 35.8};
double avgHot = DoubleStream.of(celsius)
.map(c -> c * 9 / 5 + 32)
.filter(f -> f > 95)
.average()
.orElse(Double.NaN);
System.out.printf("Average of hot readings: %.2f F%n", avgHot);
}
}
Average of hot readings: 98.00 F
How it works: 36.2, 38.0 and 35.8 degrees Celsius are above 95 F after conversion. printf with %.2f rounds only for display; the computed value keeps full precision.
Example 2: Fractional steps (Java 9+)
Build a price list with discount rates from 0% to 30% in 7.5% steps.
import java.util.stream.DoubleStream;
public class DiscountSteps {
public static void main(String[] args) {
double price = 2400.0;
DoubleStream.iterate(0.0, rate -> rate <= 0.30, rate -> rate + 0.075)
.forEach(rate -> System.out.printf("%4.1f%% off -> %7.2f%n", rate * 100, price * (1 - rate)));
}
}
0.0% off -> 2400.00 7.5% off -> 2220.00 15.0% off -> 2040.00 22.5% off -> 1860.00 30.0% off -> 1680.00
How it works: The three-argument iterate() (Java 9) adds 0.075 to the rate until it passes 0.30. Repeated floating-point addition can drift slightly, so whether the last step is included depends on rounding; the Mistakes section shows a drift-free alternative based on integers.
Example 3: Statistics for a set of measurements (Java 16+)
Summarise delivery distances in kilometres for a route planner.
import java.util.DoubleSummaryStatistics;
import java.util.List;
public class DistanceStats {
record Delivery(String id, double km) { }
public static void main(String[] args) {
List<Delivery> deliveries = List.of(
new Delivery("D1", 12.4), new Delivery("D2", 3.85), new Delivery("D3", 27.1), new Delivery("D4", 8.0));
DoubleSummaryStatistics stats = deliveries.stream().mapToDouble(Delivery::km).summaryStatistics();
System.out.printf("count %d, total %.2f km, shortest %.2f km, longest %.2f km, average %.3f km%n",
stats.getCount(), stats.getSum(), stats.getMin(), stats.getMax(), stats.getAverage());
}
}
count 4, total 51.35 km, shortest 3.85 km, longest 27.10 km, average 12.838 km
How it works: mapToDouble() and summaryStatistics() give every figure a planner needs in one pass.
Example 4: NaN spreads through a stream
A faulty sensor sends NaN. See how it affects the average, and filter it out.
import java.util.stream.DoubleStream;
public class NaNHandling {
public static void main(String[] args) {
double[] humidity = {41.0, 43.5, Double.NaN, 44.0};
double raw = DoubleStream.of(humidity).average().orElse(0);
double clean = DoubleStream.of(humidity).filter(h -> !Double.isNaN(h)).average().orElse(0);
System.out.println("Raw average: " + raw);
System.out.println("Clean average: " + clean);
}
}
Raw average: NaN Clean average: 42.833333333333336
How it works: One NaN turns the whole average into NaN. Filter invalid values with Double.isNaN() (and Double.isFinite() for infinities) before aggregating.
4. Real-World Use Cases
- IoT and monitoring: temperature, humidity and latency averages.
- Analytics: conversion rates, percentages and weighted scores.
- Geography: distances and coordinates.
- Science and engineering: measurements where small rounding errors are acceptable.
5. Important Points
- Approximate: results are close, not exact; never compare doubles with
==after arithmetic. - Money: use
longminor units orBigDecimal, notdouble. - NaN and Infinity propagate; filter them early.
- Parallel sums may differ slightly from sequential ones.
- Empty streams:
average(),min()andmax()return emptyOptionalDouble.
6. Choosing the Right Number Type
| Need | Use | Why |
|---|---|---|
| Measurements and ratios | DoubleStream | Fast; small errors acceptable |
| Money, exact decimals | LongStream of paise or Stream<BigDecimal> | Exact results |
| Fractional steps | IntStream mapped to doubles | No accumulated drift |
| Rounded display | printf("%.2f") or BigDecimal.setScale() | Rounds only the output |
7. Common Mistakes and Best Practices
Stepping with repeated addition
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
public class DriftFreeSteps {
public static void main(String[] args) {
long added = DoubleStream.iterate(0.0, x -> x <= 1.0, x -> x + 0.1).count();
long divided = IntStream.rangeClosed(0, 10).mapToDouble(i -> i / 10.0).count();
System.out.println("Repeated +0.1 produced " + added + " values (expected 11)");
System.out.println("i / 10.0 produced " + divided + " values");
}
}
Repeated +0.1 produced 11 values (expected 11) i / 10.0 produced 11 values
Here both happen to produce 11 values, but the repeated-addition version reaches 0.9999999999999999 instead of 1.0 for its last value, and with other limits it can produce one value too many or too few. Stepping through integers and dividing avoids that drift entirely.
Other mistakes to avoid
- Using
doublefor currency totals. - Comparing averages with
==. Compare with a tolerance, such asMath.abs(a - b) < 1e-9. - Ignoring
NaNfrom bad input.
8. Summary
DoubleStreamprocessesdoublevalues without boxing.- Results are approximate; filter
NaNand avoid==comparisons. - Build fractional steps from integers to avoid drift.
- Do not use
doublefor money.
9. References
Frequently Asked Questions (FAQ)
Q1. What is DoubleStream in Java?
DoubleStream is the primitive specialisation of Stream for double values, added in Java 8. It provides sum(), average(), min(), max() and summaryStatistics() without boxing.
Q2. Why is there no DoubleStream.range()?
Ranges of fractional values are ambiguous because of rounding. Build them from an IntStream, for example IntStream.rangeClosed(0, 10).mapToDouble(i -> i / 10.0).
Q3. Is DoubleStream.sum() exact?
No. It uses compensated summation to reduce error, but double values are approximate, so results can differ slightly from exact decimal arithmetic.
Q4. Should I use DoubleStream for money?
No. Use whole minor units in a LongStream, such as paise, or BigDecimal, which represent decimal amounts exactly.
Q5. What happens if a DoubleStream contains NaN?
NaN propagates: sums and averages become NaN. Filter it out with Double.isNaN() before aggregating.