Java Reference ยท Streams and Functional
LongStream and DoubleStream
Reference for Java LongStream and DoubleStream: primitive long and double streams, ranges, sums, averages, conversions and precision pitfalls.
LongStream and DoubleStream are the primitive stream types for long and double values, alongside IntStream. They avoid boxing and provide numeric terminals: sum(), average(), min(), max() and summaryStatistics().
LongStream is the right choice for large totals, counters and ranges beyond int. DoubleStream suits measurements and statistics. There is no FloatStream or ShortStream; widen those values to double or int.
long big = LongStream.rangeClosed(1, 20).reduce(1L, (a, b) -> a * b); // 20! double avg = DoubleStream.of(1.5, 2.5).average().getAsDouble();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public interface LongStream extends BaseStream<Long, LongStream> public interface DoubleStream extends BaseStream<Double, DoubleStream>
| Member | LongStream |
DoubleStream |
|---|---|---|
| Factories | of, empty, range, rangeClosed, iterate, generate |
of, empty, iterate, generate (no ranges) |
| Intermediate | map, filter, flatMap, sorted, distinct, limit, skip, peek |
same |
| Conversions | mapToInt, mapToDouble, mapToObj, boxed, asDoubleStream |
mapToInt, mapToLong, mapToObj, boxed |
| Terminals | sum (long), average, min/max (OptionalLong), summaryStatistics, toArray |
sum (double), average, min/max (OptionalDouble), summaryStatistics, toArray |
Usage notes
- Overflow:
LongStream.sum()still wraps around beyondLong.MAX_VALUE; useMath.addExactin areduceorBigIntegerwhen that matters. - Narrowing needs explicit conversion:
mapToInt(l -> (int) l)silently truncates; useMath.toIntExactto fail loudly. - Double sums:
DoubleStream.sum()uses compensated summation, but decimal fractions such as 0.1 are still inexact. UseBigDecimalfor money. NaNand sorting:sorted()on doubles placesNaNlast and orders-0.0before0.0.- Random streams:
Random.doubles()andlongs()return these stream types; seed the generator for repeatable output. - Boxing:
boxed()yieldsStream<Long>orStream<Double>for use with collectors. - Averages:
average()of an empty stream is an emptyOptionalDouble, notNaN.