Skip to content
Tutorials Center
My learning

Topics

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.

Java
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

Java LongStream for big numbers

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.

Java DoubleStream and precision

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

Java
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 beyond Long.MAX_VALUE; use Math.addExact in a reduce or BigInteger when that matters.
  • Narrowing needs explicit conversion: mapToInt(l -> (int) l) silently truncates; use Math.toIntExact to fail loudly.
  • Double sums: DoubleStream.sum() uses compensated summation, but decimal fractions such as 0.1 are still inexact. Use BigDecimal for money.
  • NaN and sorting: sorted() on doubles places NaN last and orders -0.0 before 0.0.
  • Random streams: Random.doubles() and longs() return these stream types; seed the generator for repeatable output.
  • Boxing: boxed() yields Stream<Long> or Stream<Double> for use with collectors.
  • Averages: average() of an empty stream is an empty OptionalDouble, not NaN.