Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Why do IntStream, LongStream and DoubleStream exist? Show how to convert between object and primitive streams and name operations only primitive streams have.

IntStream, LongStream and DoubleStream exist so that numeric pipelines can work on raw int, long and double values without boxing each one into an Integer, Long or Double object, and so that they can offer numeric operations that a Stream of objects cannot. We convert with mapToInt, mapToLong and mapToDouble, and back with boxed() or mapToObj. Only primitive streams have sum, average, summaryStatistics, and the range and rangeClosed factories; average returns an OptionalDouble that is empty for an empty stream, and IntStream.range(0, n) replaces many index loops.

Why this question is asked

Numeric code is everywhere in business applications: totals, counts, averages, scores. Writing it with a plain Stream<Integer> works, but it is slower than it needs to be and misses useful operations. Interviewers ask this to check that we know why the primitive streams exist and can move between object and primitive streams fluently. In this answer, we will recap boxing and why it costs, look at the three primitive stream types, practise converting in both directions, go through the operations only primitive streams have, and see how IntStream.range replaces index loops.

1A Quick Recap of Boxing

Java has primitive types, such as int, long and double, which hold a value directly, and wrapper classes, such as Integer, Long and Double, which are objects that hold a value. Generics only work with objects, so a Stream<T> of numbers must be a Stream<Integer>. Turning an int into an Integer is called boxing, and turning it back is unboxing. The compiler does both automatically, which is why the cost is easy to miss.

Each boxing can allocate a new object of about 16 bytes, apart from small values such as -128 to 127, which come from a cache. Summing a million values in a Stream<Integer> can therefore create many objects and unbox each one for every addition. The primitive streams avoid this entirely by working on the raw values.

2The Three Primitive Streams

IntStream, LongStream and DoubleStream mirror Stream but carry primitive values. Their lambdas use primitive functional interfaces, such as IntPredicate and IntUnaryOperator, so no boxing happens inside the pipeline. There are no ByteStream, ShortStream, CharStream or FloatStream; smaller integer types widen to int, and float to double. String.chars(), for example, returns an IntStream of character codes.

Java
IntStream ints = IntStream.of(3, 1, 4);
LongStream longs = LongStream.rangeClosed(1, 3); // 1, 2, 3
DoubleStream doubles = DoubleStream.of(2.5, 3.5);
long letters = "hello world".chars().filter(Character::isLetter).count(); // 10

3Converting Between Object and Primitive Streams

To go from objects to primitives, use mapToInt, mapToLong or mapToDouble with a function that extracts a number. To go back, use boxed(), which wraps each value, or mapToObj, which turns each value into any object. Between primitive types there are asLongStream and asDoubleStream for widening.

Java
record Order(String id, int quantity, double price) {}
List<Order> orders = List.of(new Order("a", 2, 9.5), new Order("b", 5, 3.0));
int totalQty = orders.stream().mapToInt(Order::quantity).sum(); // 7
double revenue = orders.stream()
.mapToDouble(o -> o.quantity() * o.price()).sum(); // 34.0
List<Integer> squares = IntStream.rangeClosed(1, 4)
.map(x -> x * x)
.boxed() // Stream<Integer>
.toList(); // [1, 4, 9, 16]
List<String> labels = IntStream.range(0, 3)
.mapToObj(i -> "item-" + i) // Stream<String>
.toList(); // [item-0, item-1, item-2]
long big = IntStream.of(1, 2, 3).asLongStream().map(x -> x * 1_000_000_000L).sum(); // 6000000000
Step throughMoving between stream types
  1. Stream<Order>objects; generic operations only
  2. mapToInt / mapToLong / mapToDoubleextract a number from each object
  3. IntStream / LongStream / DoubleStreamraw values; sum, average, range
  4. boxed() or mapToObj(...)back to objects when we need a List or other objects
  5. Stream<Integer> or Stream<String>for toList, collectors and generic code

5 layers, from the top down. Step through them one at a time.

Go down to primitives for the numeric work, and come back up only when needed.

Notice that a primitive stream has no toList method, because List cannot hold primitives. We call boxed() first, or collect into an array with toArray(), which returns an int[]. Also note that map on an IntStream must return an int; to produce anything else we use mapToObj, mapToLong or mapToDouble.

4Operations Only Primitive Streams Have

Primitive streams add numeric terminal operations. sum() returns the total in the stream's own type. average() returns an OptionalDouble, empty when there are no elements, because the average of nothing is undefined. max() and min() return OptionalInt and its relatives. summaryStatistics() computes count, sum, min, average and max in a single pass.

Java
int sum = IntStream.of(10, 20, 30).sum(); // 60
OptionalDouble avg = IntStream.of(10, 20, 30).average(); // OptionalDouble[20.0]
OptionalDouble none = IntStream.empty().average(); // OptionalDouble.empty
double safe = none.orElse(0.0); // 0.0
IntSummaryStatistics stats = IntStream.of(10, 20, 30).summaryStatistics();
System.out.println(stats.getMin() + " " + stats.getMax() + " " + stats.getAverage()); // 10 30 20.0
System.out.println(IntStream.empty().sum()); // 0

Notice the difference between sum and average on an empty stream. The sum of nothing is 0, a perfectly good number, so sum returns a plain int. The average of nothing has no sensible value, so average returns an OptionalDouble and makes us decide, with orElse or orElseThrow, what an empty input means in our domain. summaryStatistics is useful when we need several of these numbers, because it reads the stream once instead of once per statistic.

Stream<T> has no sum or average; we would need collectors such as Collectors.summingInt or averagingDouble, which still box. On the other hand, primitive streams have no collect(Collectors...) form, which is one more reason to box back when we need groupings or lists.

5Replacing Index Loops With IntStream.range

IntStream.range(start, end) produces start up to end - 1, and rangeClosed(start, end) includes end. Many classic index loops become one line, and the range splits perfectly if we ever need a parallel stream.

Java
// Classic loop
for (int i = 0; i < names.size(); i++) {
System.out.println(i + ": " + names.get(i));
}
// The same with a range
IntStream.range(0, names.size())
.mapToObj(i -> i + ": " + names.get(i))
.forEach(System.out::println);
// 0: alice
// 1: bob
int[] evensUnder10 = IntStream.range(0, 10).filter(i -> i % 2 == 0).toArray(); // [0, 2, 4, 6, 8]

Use it where the index itself is the data, such as pairing positions with values, generating test data, or iterating two lists in step. For simply visiting each element of a list, the enhanced for loop or list.stream() remains clearer.

6Follow-up questions

Why is there no CharStream or FloatStream?

The designers chose to limit the number of specialised types, since each one multiplies the API surface. char values fit in int, so String.chars() returns an IntStream, and float widens to double without loss. Three primitive streams cover nearly all numeric work.

Is boxing always slow enough to matter?

Not always. For a few hundred elements the difference is negligible. It matters in hot paths and large datasets, where allocation pressure shows up in profilers and garbage collection. Using mapToInt for numeric work is cheap to write, so it is a good habit regardless.

Can the sum of an IntStream overflow?

Yes. IntStream.sum returns an int and wraps silently on overflow. For large totals, convert with mapToLong or asLongStream first, or use LongStream.reduce(0, Math::addExact) when an overflow should throw instead.

7Conclusion

In this answer, we saw that IntStream, LongStream and DoubleStream exist to avoid boxing every number into an object and to provide numeric operations. We converted from objects with mapToInt, mapToLong and mapToDouble and back with boxed and mapToObj, used sum, average, max and summaryStatistics, noted that average returns an OptionalDouble that is empty for an empty stream while sum returns 0, and replaced index loops with IntStream.range and rangeClosed.

What to say in the interviewAbout 80 seconds aloud

Open with

The primitive streams exist because Stream<T> only works with objects, so a Stream<Integer> boxes every number into an Integer and unboxes it for every operation, which allocates objects and slows numeric code.

Then, if they want more

IntStream, LongStream and DoubleStream work on raw values with primitive functional interfaces, so there is no boxing in the pipeline, and they add numeric operations. To get into one, I use mapToInt, mapToLong or mapToDouble, for example orders.stream().mapToInt(Order::quantity).sum().

To get back, boxed() wraps each value, which I need before toList or collectors, and mapToObj turns each value into any object, like building labels from indices. There are also asLongStream and asDoubleStream for widening.

Operations only primitive streams have are sum, average, min and max returning OptionalInt and so on, summaryStatistics which computes count, sum, min, average and max in one pass, and the range and rangeClosed factories.

One detail worth knowing: sum of an empty stream is 0, but average returns an OptionalDouble that is empty, because the average of nothing is undefined, so I decide with orElse what that means. And IntStream.range(0, n) replaces many index loops, especially when the index itself matters, like pairing positions with values.

I also keep in mind that IntStream.sum can overflow, so for big totals I use mapToLong.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why do IntStream, LongStream and DoubleStream exist? Show how to convert between object...": https://scrivio-interview-library.netlify.app/java/streams/ff320656b9/