Java Primitive Streams: IntStream, LongStream, DoubleStream and Summary Statistics (OCP 21)
Primitive streams for the OCP 21 exam: IntStream, LongStream and DoubleStream, range and rangeClosed, sum, average, min and max, OptionalInt, OptionalLong and OptionalDouble, mapping between every stream type and the functional interfaces involved, boxed, and summaryStatistics.
kvi5hnuCode Sprout team member6 min readOn this page
A Stream<Integer> holds Integer objects. Summing one means unboxing every element, and Stream has no sum() method to begin with. Java has three primitive streams for numeric work:
| Stream | Element type | Also used for |
|---|---|---|
IntStream | int | byte, short, char (widened to int) |
LongStream | long | |
DoubleStream | double | float (widened to double) |
There's no FloatStream, CharStream or BooleanStream. On the exam, Stream with a capital S means the generic Stream<T> interface. Lowercase "stream" can mean any of the four.
int total = Stream.of(1, 2, 3).reduce(0, Integer::sum); // 6, the generic way
int same = Stream.of(1, 2, 3).mapToInt(x -> x).sum(); // 6, via an IntStream
Creating primitive streams
Primitive streams have the same factory methods as Stream, plus number ranges:
DoubleStream.empty();
DoubleStream.of(3.14);
IntStream.of(1, 2, 3);
DoubleStream.generate(Math::random); // infinite
DoubleStream.iterate(8, d -> d / 2); // 8.0, 4.0, 2.0, ...
IntStream.iterate(1, i -> i <= 9, i -> i + 4); // 1, 5, 9
IntStream.range(1, 6); // 1, 2, 3, 4, 5 end EXCLUSIVE
IntStream.rangeClosed(1, 5); // 1, 2, 3, 4, 5 end INCLUSIVE
LongStream.rangeClosed(1, 3); // 1L, 2L, 3L
rangeandrangeClosedexist only onIntStreamandLongStream, not onDoubleStream.- An empty or "backwards" range, such as
range(5, 5)orrange(6, 1), produces no elements. It doesn't throw.
Other sources: Arrays.stream(int[]), "text".chars() (an IntStream of character codes), and new Random().ints().
Methods only primitive streams have
| Method | IntStream | LongStream | DoubleStream |
|---|---|---|---|
sum() | int | long | double |
average() | OptionalDouble | OptionalDouble | OptionalDouble |
min() / max() (no arguments) | OptionalInt | OptionalLong | OptionalDouble |
summaryStatistics() | IntSummaryStatistics | LongSummaryStatistics | DoubleSummaryStatistics |
boxed() | Stream<Integer> | Stream<Long> | Stream<Double> |
Exam points in this table:
sum()returns a plain number, never an optional. The sum of an empty stream is0.average()always returns anOptionalDouble, even forIntStream, because an average can have a fraction. It's empty for an empty stream.min()andmax()take no comparator on primitive streams. OnStream<T>they require one.- Primitive streams have no
toList()and nocollect(Collector). Useboxed()first:IntStream.range(0, 3).boxed().toList().
Primitive optionals
OptionalInt, OptionalLong and OptionalDouble work like Optional, with primitive-flavored names:
OptionalInt | OptionalLong | OptionalDouble | |
|---|---|---|---|
| get the value | getAsInt() | getAsLong() | getAsDouble() |
orElseGet takes | IntSupplier | LongSupplier | DoubleSupplier |
returned by min/max of | IntStream | LongStream | DoubleStream |
OptionalDouble avg = IntStream.rangeClosed(1, 10).average();
avg.ifPresent(System.out::println); // 5.5
avg.getAsDouble(); // 5.5
avg.get(); // DOES NOT COMPILE: no get() on OptionalDouble
IntStream.empty().average(); // OptionalDouble.empty
IntStream.empty().max().orElse(-1); // -1
Primitive optionals have no map, filter or flatMap. Their assignments are strict too: Optional<Integer> m = intStream.max(); doesn't compile, because max() returns an OptionalInt.
Mapping between stream types

| From \ To | Stream<R> | IntStream | LongStream | DoubleStream |
|---|---|---|---|---|
Stream<T> | map | mapToInt | mapToLong | mapToDouble |
IntStream | mapToObj | map | mapToLong | mapToDouble |
LongStream | mapToObj | mapToInt | map | mapToDouble |
DoubleStream | mapToObj | mapToInt | mapToLong | map |
The patterns:
- Mapping to the same kind of stream is
map. - Mapping a primitive stream to objects is
mapToObj. - Everything else is
mapTo+ the target type.
map on a Stream can't produce an IntStream: IntStream x = stream.map(String::length) doesn't compile. Use mapToInt. Likewise, map on an IntStream returns an IntStream, never a Stream<Integer>.
The functional interfaces follow a similar pattern:
| From \ To | object R | int | long | double |
|---|---|---|---|---|
T (object) | Function<T,R> | ToIntFunction<T> | ToLongFunction<T> | ToDoubleFunction<T> |
int | IntFunction<R> | IntUnaryOperator | IntToLongFunction | IntToDoubleFunction |
long | LongFunction<R> | LongToIntFunction | LongUnaryOperator | LongToDoubleFunction |
double | DoubleFunction<R> | DoubleToIntFunction | DoubleToLongFunction | DoubleUnaryOperator |
- Same type in and out: a
UnaryOperator. - Primitive to object: no "To" in the name (
IntFunction). - Object to primitive:
ToXFunction. - Primitive to another primitive:
XToYFunction.
A lambda in mapToInt must return an int. doubleStream.mapToInt(d -> d) doesn't compile without a cast, because double doesn't narrow to int automatically.
More conversions:
boxed()turns a primitive stream into a stream of wrapper objects. It's the same asmapToObj(x -> x).asLongStream()andasDoubleStream()widen anIntStream(or aLongStreamtodouble).flatMapToInt,flatMapToLongandflatMapToDoubleonStream<T>flatten into a primitive stream:words.flatMapToInt(String::chars).
Summary statistics
min() and max() are both terminal, so one stream can't give you both. summaryStatistics() computes everything in one pass:
static int spread(IntStream values) {
IntSummaryStatistics stats = values.summaryStatistics();
if (stats.getCount() == 0) throw new IllegalStateException("no data");
return stats.getMax() - stats.getMin();
}
| Method | Returns | Empty stream |
|---|---|---|
getCount() | long | 0 |
getSum() | long for int and long statistics, double for double statistics | 0 |
getAverage() | double | 0.0 |
getMin() | int/long/double | the largest value: Integer.MAX_VALUE, Long.MAX_VALUE or Double.POSITIVE_INFINITY |
getMax() | int/long/double | the smallest value: Integer.MIN_VALUE, Long.MIN_VALUE or Double.NEGATIVE_INFINITY |
The statistics methods return plain values, not optionals. On an empty stream they return those sentinel values, so check getCount() first, as spread does. Note that IntSummaryStatistics.getSum() is a long, which protects against overflow.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Primitive streams still cover only
int,longanddouble, and Java 22 through 25 added no primitive stream types or methods.
Exam traps from this article
A complete example
The program analyzes a week of runs. It creates primitive streams from ranges and iterate, maps records to int and double streams for sums and averages, and handles empty primitive optionals. It gets two statistics from one summaryStatistics(), maps back to objects with mapToObj and boxed, and converts between primitive types.
import java.util.DoubleSummaryStatistics;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class Solution {
record Run(String day, int minutes, double km) {}
static final List<Run> WEEK = List.of(
new Run("Mon", 32, 5.4),
new Run("Wed", 45, 7.9),
new Run("Fri", 28, 4.6),
new Run("Sun", 61, 10.2));
// max of an IntStream, or an exception if there is no data
static int longest(IntStream minutes) {
OptionalInt best = minutes.max();
return best.orElseThrow(() -> new IllegalStateException("no runs"));
}
// two statistics from ONE terminal operation
static int spread(IntStream values) {
IntSummaryStatistics stats = values.summaryStatistics();
if (stats.getCount() == 0) throw new IllegalStateException("no data");
return stats.getMax() - stats.getMin();
}
public static void main(String[] args) {
// Creating primitive streams
System.out.println("range(1, 6): " + IntStream.range(1, 6).boxed().toList()
+ ", rangeClosed(1, 5) sum: " + IntStream.rangeClosed(1, 5).sum()
+ ", LongStream.of sum: " + LongStream.of(5_000_000_000L, 1).sum());
System.out.println("halving: " + DoubleStream.iterate(8, d -> d / 2).limit(4).boxed().toList());
// Mapping from Stream<T> to primitives: mapToInt / mapToDouble
int totalMinutes = WEEK.stream().mapToInt(Run::minutes).sum();
double totalKm = WEEK.stream().mapToDouble(Run::km).sum();
OptionalDouble avgMinutes = WEEK.stream().mapToInt(Run::minutes).average();
System.out.println("total " + totalMinutes + " min, " + totalKm + " km, average "
+ avgMinutes.getAsDouble() + " min");
// Primitive optionals: getAsX, orElse, empty results
OptionalDouble none = IntStream.empty().average();
System.out.println("empty average: " + none + ", orElse: " + none.orElse(-1)
+ ", empty sum: " + IntStream.empty().sum());
// Two answers from one stream need summaryStatistics
System.out.println("longest: " + longest(WEEK.stream().mapToInt(Run::minutes))
+ ", spread: " + spread(WEEK.stream().mapToInt(Run::minutes)));
DoubleSummaryStatistics kmStats = WEEK.stream().mapToDouble(Run::km).summaryStatistics();
System.out.printf("km stats: count=%d min=%.1f max=%.1f avg=%.2f sum=%.1f%n",
kmStats.getCount(), kmStats.getMin(), kmStats.getMax(), kmStats.getAverage(), kmStats.getSum());
// Back to objects: mapToObj and boxed
List<String> paces = WEEK.stream()
.mapToDouble(r -> r.minutes() / r.km())
.mapToObj(p -> String.format("%.2f", p))
.toList();
List<Integer> squares = IntStream.rangeClosed(1, 4).map(n -> n * n).boxed().toList();
System.out.println("pace min/km: " + paces + ", squares: " + squares);
// Primitive-to-primitive mapping and flatMapToInt
long seconds = WEEK.stream().mapToInt(Run::minutes).mapToLong(m -> m * 60L).sum();
long vowels = Stream.of("Mon", "Wed", "Sun").flatMapToInt(String::chars).filter(c -> "aeiou".indexOf(c) >= 0).count();
System.out.println("seconds: " + seconds + ", vowels in day names: " + vowels);
// Error case: no data at all
try {
spread(IntStream.empty());
} catch (IllegalStateException e) {
System.out.println("spread of nothing: " + e.getMessage());
}
}
}
Output:
range(1, 6): [1, 2, 3, 4, 5], rangeClosed(1, 5) sum: 15, LongStream.of sum: 5000000001
halving: [8.0, 4.0, 2.0, 1.0]
total 166 min, 28.1 km, average 41.5 min
empty average: OptionalDouble.empty, orElse: -1.0, empty sum: 0
longest: 61, spread: 33
km stats: count=4 min=4.6 max=10.2 avg=7.03 sum=28.1
pace min/km: [5.93, 5.70, 6.09, 5.98], squares: [1, 4, 9, 16]
seconds: 9960, vowels in day names: 3
spread of nothing: no data
Points to notice:
range(1, 6)stopped at 5.rangeClosed(1, 5)included 5 and summed to 15.LongStream.of(5_000_000_000L, 1).sum()neededlong. The value doesn't fit in anint.IntStream.empty().average()wasOptionalDouble.empty, whileIntStream.empty().sum()was simply0.spreadread the max and min from a singlesummaryStatistics()call, and checkedgetCount()before trusting them.mapToDouble(...).mapToObj(...)converted primitive paces back intoStringobjects, andboxed()made the squarestoList()-able.
Common questions
Why use primitive streams at all?
They avoid boxing millions of wrapper objects, and they offer sum, average, range and summaryStatistics. For numeric work they're both faster and shorter.
Is chars() a Stream<Character>?
No, it's an IntStream of character codes. Use mapToObj(c -> (char) c) to get Character objects back.
Can I collect an IntStream into a list without boxed()?
Only with the three-argument collect(Supplier, ObjIntConsumer, BiConsumer), for example collect(ArrayList::new, ArrayList::add, ArrayList::addAll). boxed().toList() is far simpler.
Summary
IntStream,LongStreamandDoubleStreamhold primitives.int-sized types useIntStream, andfloatusesDoubleStream.- Create them with
of,empty,generate,iterate,range(exclusive) andrangeClosed(inclusive), or by mapping. - They add
sum(a plain number),average(alwaysOptionalDouble), argument-lessmin/max(primitive optionals) andsummaryStatistics. - Map between stream types with
map,mapToObj,mapToInt,mapToLong,mapToDoubleandboxed, using the matching…Functionor…UnaryOperatorinterfaces. summaryStatisticsgives count, sum, min, max and average in one pass. Check the count on empty streams.
Practice quiz
Test yourself with the primitive streams quiz: 10 exam-style questions with explanations.
Previous: Java Stream Intermediate Operations: filter, map, flatMap, sorted, distinct, limit and peek (OCP 21)
Next: Java Collectors: joining, toMap, groupingBy, partitioningBy and teeing (OCP 21)
Related reading
- Java Stream Intermediate Operations: filter, map, flatMap, sorted, distinct, limit and peek (OCP 21)
- Java Stream Terminal Operations: count, min, max, find, match, forEach, reduce and collect (OCP 21)
- Java Streams: Pipeline Flow and Creating Finite and Infinite Streams (OCP 21)
- Java Optional: Creating, Checking and Unwrapping Optional Values (OCP 21)
- Java Lambda Variables: Parameters, Locals and Effectively Final Captures (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.