Lesson · Stream API
Primitive streams: IntStream, LongStream, DoubleStream
11 min readPrimitive Streams
Boxing every number into an Integer object inside a pipeline is measurable waste. The primitive stream family removes it, adds numeric terminals like sum and average that object streams cannot offer, and brings the range loop into the fluent world.
What boxing costs
Stream<Integer> looks natural but every length, every score, every counter passes through Integer.valueOf: objects allocated, unboxed, compared via equals, cleared by the garbage collector. For a handful of elements nobody notices; for a million-element numeric pipeline it is the main cost.
The fix is a parallel family of streams whose elements are raw primitives: IntStream, LongStream and DoubleStream. Operations on them read and write int, long and double directly, so no wrapping happens at all.
words.stream().map(String::length) // Stream<Integer>: every length boxed .reduce(0, Integer::sum); words.stream().mapToInt(String::length).sum(); // IntStream: no boxing, sum is built in
Numeric pipelines · two lanes over the same data
source: ada, grace, edsger, linusboxed path
Each length is boxed to an Integer, unboxed inside the fold: object churn on every element, then reduce has to combine Integers.
result: 19
primitive path
Lengths stay raw ints the whole way; sum() is a built-in numeric terminal, no wrapping anywhere.
result: 19
half-open: includes 1, excludes 4 · matches the classic for-loop idiom
count: 3
The family and its bridges
You rarely create primitive streams directly; you convert into them from an object stream with mapToInt, mapToLong or mapToDouble, and convert back with mapToObj or boxed when you need objects again. The three numeric streams share the same toolbox: sum, min, max, average and summaryStatistics.
summaryStatistics is the gift of the family: one pass produces count, sum, min, max and average together, which otherwise means four separate terminal operations over the data.
IntSummaryStatistics stats = words.stream() .mapToInt(String::length) .summaryStatistics(); // count, sum, min, max, average in a single traversal
Ranges: the for-loop, fluent
IntStream.range(start, end) is half-open, it includes start and excludes end, and that is deliberately the classic index idiom. rangeClosed includes both ends. Both make replacing an index loop with a pipeline a direct translation instead of an off-by-one puzzle.
IntStream.range(1, 4).count(); // 3 -> [1, 2, 3] IntStream.rangeClosed(1, 4).count(); // 4 -> [1, 2, 3, 4]
min, max and average return primitive Optionals
Because an empty IntStream has no smallest element, min and max return OptionalInt, and average returns OptionalDouble. Same contract as the object Optional: the type tells you the empty case is possible, and asking for a value (getAsInt) throws if there is none.
sum and count are the two terminals with no empty-case problem: they return 0, which is why they return plain numbers.
When it pays off
Use the primitive family whenever the elements are numbers flowing through arithmetic, aggregates or comparisons: totals, averages, statistics, index walks, numeric filtering. Stay in object streams when you need the elements as objects anyway, for grouping keys or builders, since converting back and forth just moves the cost around.
A pipeline that boxes its numbers and then reduces them by hand is doing two jobs; mapToInt and its family do one, with a purpose-built terminal at the end.
One bridge is often enough
Convert into the primitive family at the moment numbers appear (after mapping to length, score, price) and stay there until you need objects again. Crossing the bridge twice in the middle of a numeric pipeline drops most of the benefit.
Interview angles
Why does Stream<Integer> perform worse than IntStream for numbers?+
Every element is boxed into an Integer object and unboxed for arithmetic. IntStream operates on raw int values with no allocation, and its numeric terminals (sum, average, summaryStatistics) avoid per-element object work entirely.
Difference between range and rangeClosed?+
range(start, end) is half-open: includes start, excludes end. rangeClosed includes both ends. range matches the classic for-loop index idiom; choose whichever makes the boundary obvious at the call site.
Why do min and max on IntStream return OptionalInt?+
The stream may be empty and then no minimum exists. OptionalInt makes that case part of the type instead of inventing a sentinel value; getAsInt throws NoSuchElementException if the stream was empty.
How do you get sum, min, max and average in one traversal?+
summaryStatistics: it consumes the stream once and returns an IntSummaryStatistics carrying count, sum, min, max and average, instead of running four terminals over the same data.
How do you get back to objects from an IntStream?+
mapToObj, or boxed to wrap into a Stream<Integer>. You need this when the next stage wants arbitrary objects, for example after generating indices you map them to strings or records.