Java Primitive Streams: IntStream, LongStream and DoubleStream
Avoid boxing with Java's IntStream, LongStream and DoubleStream. Create them with of, range, chars, codePoints and random generators, convert with mapToInt and boxed, and use sum, average, max, summaryStatistics and OptionalInt, plus the overflow and floating-point details.
kvi5hnuCode Sprout team member7 min readOn this page
So far we've often worked with a Stream<Integer>. That works, but every element is a separate Integer object on the heap, and every arithmetic step unboxes and reboxes values. For number crunching that's wasteful. The stream library therefore has three primitive streams, IntStream, LongStream and DoubleStream, which hold int, long and double values directly.
There are no streams for the other primitive types. Use an IntStream for short, char, byte and boolean values, and a DoubleStream for float.
Creating primitive streams
IntStream.of and Arrays.stream create a stream from values or from an array, optionally a range of the array:
IntStream stream = IntStream.of(1, 1, 2, 3, 5);
stream = Arrays.stream(values, from, to); // values is an int[]; to is exclusive
generate and iterate work just as for object streams. In addition, IntStream and LongStream have range and rangeClosed, which produce consecutive integers:
IntStream zeroToNinetyNine = IntStream.range(0, 100); // upper bound excluded
IntStream zeroToHundred = IntStream.rangeClosed(0, 100); // upper bound included
IntStream.range(0, n) is the stream equivalent of for (int i = 0; i < n; i++), and you'll use it constantly, such as for iterating over array indexes.
Characters and code points
CharSequence, and therefore String, has two methods that return an IntStream:
chars()yields the UTF-16 code units (charvalues).codePoints()yields the Unicode code points.
The difference matters for characters outside the Basic Multilingual Plane, such as most emoji, which take two chars. The pirate flag 🏴☠️ is even made of four code points: a black flag, a zero-width joiner, a skull and crossbones, and a variation selector. In the demo, "Ahoy 🏴☠️" has 10 chars but 9 code points. Part 2 covers text encodings in detail.
To turn a stream of code points back into a string, collect them into a StringBuilder:
String letters = s.codePoints().filter(Character::isLetter)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
Random numbers
RandomGenerator (and therefore Random, SplittableRandom and ThreadLocalRandom) has ints, longs and doubles methods that return primitive streams of random numbers, infinite or with a given size and bounds:
IntStream diceRolls = RandomGenerator.getDefault().ints(100, 1, 7); // 100 values from 1 to 6
Converting between object and primitive streams
mapToInt, mapToLong and mapToDouble turn an object stream into a primitive stream:
IntStream lengths = words.mapToInt(String::length);
Going the other way, boxed() wraps each value, and mapToObj maps each value to an object:
Stream<Integer> integers = IntStream.range(0, 100).boxed();
Stream<String> labels = IntStream.rangeClosed(1, 3).mapToObj(i -> "#" + i);
Between primitive streams there are asLongStream() and asDoubleStream() for widening, and mapToLong, mapToDouble and mapToInt for arbitrary conversions.
What's different about primitive streams
Most methods are the same as for object streams, but there are some notable differences:
toArray()returns a primitive array, such as anint[]. NoString[]::newtrick needed.- Methods with an optional result return an
OptionalInt,OptionalLongorOptionalDouble. They work likeOptional, but the getters aregetAsInt(),getAsLong()andgetAsDouble().orElse,orElseThrow,ifPresentandisPresentare there as usual. They lackmap,filterandflatMap. - There are terminal methods
sum,average,maxandmin, with no comparator needed.sum()returns0for an empty stream.average(),max()andmin()return an empty optional. summaryStatistics()returns anIntSummaryStatistics(orLong/Doubleversion) with count, sum, average, minimum and maximum in one pass.mapon anIntStreammust produce anint. To produce something else, usemapToObj,mapToLongormapToDouble.mapMultitakes anIntConsumersink, so each value can expand to any number ofints without boxing.
Overflow and floating-point sums
IntStream.sum() returns an int and overflows silently, just like +. Summing Integer.MAX_VALUE and 1 gives -2147483648. If the total might exceed about two billion, convert first: intStream.asLongStream().sum(). (IntSummaryStatistics.getSum() returns a long, so it doesn't overflow for reasonable counts.)
DoubleStream.sum() and average() use a compensated summation algorithm that reduces rounding error. That's why adding 0.1 ten times with DoubleStream.sum() gives exactly 1.0, while a plain loop gives 0.9999999999999999. The result can still differ in the last bits from a naive loop, and in parallel streams the order of additions can change the result slightly. For money, use BigDecimal or integer cents, not double.
A complete example
import java.util.*;
import java.util.random.*;
import java.util.stream.*;
public class Solution {
public static void main(String[] args) {
// creating primitive streams
IntStream fib = IntStream.of(1, 1, 2, 3, 5, 8);
System.out.println("of: " + Arrays.toString(fib.toArray()));
int[] values = { 10, 20, 30, 40, 50 };
System.out.println("Arrays.stream(values, 1, 4): " + Arrays.toString(Arrays.stream(values, 1, 4).toArray()));
System.out.println("range(5, 10): " + Arrays.toString(IntStream.range(5, 10).toArray()));
System.out.println("rangeClosed(5, 10): " + Arrays.toString(IntStream.rangeClosed(5, 10).toArray()));
System.out.println("iterate with a condition: "
+ Arrays.toString(IntStream.iterate(1, i -> i < 200, i -> i * 3).toArray()));
// characters and code points
String greeting = "Ahoy 🏴☠️";
System.out.println("length(): " + greeting.length() + ", chars: " + greeting.chars().count()
+ ", code points: " + greeting.codePoints().count());
System.out.println("code points: " + greeting.codePoints()
.mapToObj(c -> "U+%04X".formatted(c)).collect(Collectors.joining(" ")));
System.out.println("letters only: " + "a1b2c3".chars().filter(Character::isLetter)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append));
// random numbers with a fixed seed
RandomGenerator generator = RandomGenerator.of("L64X128MixRandom");
System.out.println("random stream is an IntStream: " + (generator.ints(5, 1, 7) instanceof IntStream));
Random seeded = new Random(42);
System.out.println("dice rolls: " + Arrays.toString(seeded.ints(5, 1, 7).toArray()));
// converting between object and primitive streams
List<String> words = List.of("primitive", "streams", "avoid", "boxing");
IntStream lengths = words.stream().mapToInt(String::length);
System.out.println("lengths: " + Arrays.toString(lengths.toArray()));
List<Integer> boxed = IntStream.range(0, 5).boxed().toList();
System.out.println("boxed: " + boxed);
int total = boxed.stream().mapToInt(i -> i).sum();
System.out.println("unboxed sum: " + total);
System.out.println("mapToObj: " + IntStream.rangeClosed(1, 3).mapToObj(i -> "#" + i).toList());
System.out.println("asLongStream: " + IntStream.of(Integer.MAX_VALUE, 1).asLongStream().sum());
// terminal operations unique to primitive streams
System.out.println("sum: " + IntStream.of(values).sum());
System.out.println("average: " + IntStream.of(values).average());
System.out.println("max: " + IntStream.of(values).max().getAsInt());
System.out.println("average of nothing: " + IntStream.empty().average());
IntSummaryStatistics stats = words.stream().mapToInt(String::length).summaryStatistics();
System.out.println("stats: " + stats);
// int overflow in sum
System.out.println("int sum overflows: " + IntStream.of(Integer.MAX_VALUE, 1).sum());
// OptionalInt API
OptionalInt firstEven = IntStream.of(3, 5, 8, 9).filter(n -> n % 2 == 0).findFirst();
System.out.println("first even: " + firstEven.getAsInt() + ", orElse: "
+ IntStream.of(1, 3).filter(n -> n % 2 == 0).findFirst().orElse(-1));
// mapMulti on primitive streams: each number and its negation
System.out.println("mapMulti: " + Arrays.toString(IntStream.of(1, 2, 3)
.mapMulti((n, sink) -> { sink.accept(n); sink.accept(-n); }).toArray()));
// DoubleStream
double[] prices = { 9.99, 4.5, 12.25 };
System.out.println("total price: " + DoubleStream.of(prices).sum());
System.out.println("0.1 ten times, DoubleStream.sum: " + DoubleStream.generate(() -> 0.1).limit(10).sum());
double loopSum = 0;
for (int i = 0; i < 10; i++) loopSum += 0.1;
System.out.println("0.1 ten times, plain loop: " + loopSum);
}
}
of: [1, 1, 2, 3, 5, 8]
Arrays.stream(values, 1, 4): [20, 30, 40]
range(5, 10): [5, 6, 7, 8, 9]
rangeClosed(5, 10): [5, 6, 7, 8, 9, 10]
iterate with a condition: [1, 3, 9, 27, 81]
length(): 10, chars: 10, code points: 9
code points: U+0041 U+0068 U+006F U+0079 U+0020 U+1F3F4 U+200D U+2620 U+FE0F
letters only: abc
random stream is an IntStream: true
dice rolls: [3, 4, 1, 3, 1]
lengths: [9, 7, 5, 6]
boxed: [0, 1, 2, 3, 4]
unboxed sum: 10
mapToObj: [#1, #2, #3]
asLongStream: 2147483648
sum: 150
average: OptionalDouble[30.0]
max: 50
average of nothing: OptionalDouble.empty
stats: IntSummaryStatistics{count=4, sum=27, min=5, average=6.750000, max=9}
int sum overflows: -2147483648
first even: 8, orElse: -1
mapMulti: [1, -1, 2, -2, 3, -3]
total price: 26.740000000000002
0.1 ten times, DoubleStream.sum: 1.0
0.1 ten times, plain loop: 0.9999999999999999
The dice rolls use a Random with a fixed seed, so they're the same on every run.
Common questions
How do I turn an IntStream into a List<Integer>?
intStream.boxed().toList(). There is no list of primitive int values in the standard library, so the elements must be boxed at this point.
How do I sum a List<Integer>?
list.stream().mapToInt(Integer::intValue).sum(). For large totals, use mapToLong so that the sum does not overflow.
average() returns an OptionalDouble. How do I get a plain double?
stream.average().orElse(0.0) if 0 is a sensible value for "no data", or orElseThrow() if empty input is an error. getAsDouble() throws NoSuchElementException on an empty stream, just like get().
Why is there no CharStream, FloatStream or BooleanStream?
The designers limited the number of specialized interfaces, since each one needs dozens of methods and helper types. IntStream covers char, short, byte and boolean values, and DoubleStream covers float with no loss of precision.
Is IntStream.range(0, n).forEach(...) slower than a for loop?
After JIT compilation the difference is usually small, but a plain loop is simpler when you only need the index for side effects. range shines when the indexes feed a pipeline, as in range(0, n).filter(...).map(...).
How do I get random numbers in a range?
random.ints(count, origin, bound) gives count numbers from origin (inclusive) to bound (exclusive). Without count, the stream is infinite; add limit or a short-circuiting terminal operation.
API reference
java.util.stream.IntStream (similar for LongStream, and for DoubleStream without range)
| Method | Description |
|---|---|
static IntStream range(int startInclusive, int endExclusive), rangeClosed(int startInclusive, int endInclusive) | consecutive integers with step 1 |
static IntStream of(int... values) | a stream of the given values |
int[] toArray() | an array of the elements |
int sum(), OptionalDouble average(), OptionalInt max(), OptionalInt min() | arithmetic terminal operations |
IntSummaryStatistics summaryStatistics() | count, sum, average, max and min |
Stream<Integer> boxed() | a stream of wrapper objects |
<U> Stream<U> mapToObj(IntFunction<? extends U> mapper) | maps to an object stream |
LongStream asLongStream(), DoubleStream asDoubleStream() | widening conversions |
java.util.stream.Stream<T>
| Method | Description |
|---|---|
mapToInt(ToIntFunction<? super T> mapper), mapToLong(...), mapToDouble(...) | a primitive stream of the mapped values |
java.util.Arrays
| Method | Description |
|---|---|
static IntStream stream(int[] array), stream(int[] array, int from, int to) | a stream of the array's elements; also for long[] and double[] |
java.lang.CharSequence
| Method | Description |
|---|---|
IntStream chars() | the UTF-16 code units |
IntStream codePoints() | the Unicode code points |
java.util.random.RandomGenerator (Java 17)
| Method | Description |
|---|---|
IntStream ints(), ints(long size), ints(int origin, int bound), ints(long size, int origin, int bound) | random integers; also longs and doubles |
java.util.OptionalInt (similar for OptionalLong, OptionalDouble)
| Method | Description |
|---|---|
int getAsInt(), orElse(int other), orElseThrow() | the value, or a default, or an exception when empty |
boolean isPresent(), void ifPresent(IntConsumer action) | test for or consume the value |
Summary
IntStream,LongStreamandDoubleStreamstore primitive values without boxing.- Create them with
of,Arrays.stream,range,rangeClosed,generate,iterate,chars,codePointsand the random generators'ints,longsanddoubles. - Convert with
mapToIntand friends and back withboxedormapToObj. Unbox aStream<Integer>withmapToInt(i -> i). - Primitive streams add
sum,average,max,minandsummaryStatistics, and returnOptionalInt,OptionalLongorOptionalDouble. IntStream.sum()can overflow.DoubleStream.sum()uses compensated summation.
Practice Questions
Why doesn't stream.mapToInt(Function.identity()) compile for a Stream<Integer>?
mapToInt needs a ToIntFunction<Integer>. Function.identity() returns a Function<Integer, Integer>, a different interface, and Java never converts one functional interface object into another. A lambda i -> i is compiled directly as a ToIntFunction, with automatic unboxing in its body.
How do you sum all ints in an int[] array, and what changes if the result can exceed two billion?
Arrays.stream(array).sum(). For large totals use Arrays.stream(array).asLongStream().sum(), because IntStream.sum() returns an int and overflows silently.
Why does "😀".chars().count() return 2 but "😀".codePoints().count() return 1?
The emoji's code point is above U+FFFF, so UTF-16 represents it with two chars, a surrogate pair. chars() streams the code units and codePoints() streams whole code points.
What do IntStream.empty().sum() and IntStream.empty().max() return?
0 and OptionalInt.empty. A sum of nothing is zero, but there's no maximum of nothing.
Print the squares of 1 to 10 as a comma-separated string using a primitive stream.
IntStream.rangeClosed(1, 10).map(i -> i * i).mapToObj(Integer::toString).collect(Collectors.joining(", ")). mapToObj is needed because joining works on an object stream of CharSequences.
Previous: Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism
Next: Java Parallel Streams: When They Help, Ordering and Thread Safety
Related reading
- Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism
- Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
- Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect
- Implementing Custom Java Collectors with Collector.of
- Java Downstream Collectors: counting, mapping, filtering, teeing and More

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.