Boxing and Unboxing in Java Streams
Boxing is the conversion of a primitive value such as int into its wrapper object such as Integer; unboxing is the reverse. Java has done this automatically (autoboxing) since Java 5. In the Stream API, since Java 8, boxing appears whenever numbers travel through a Stream<Integer> instead of an IntStream.
This tutorial shows the methods that convert between object and primitive streams, what boxing costs, the null and identity pitfalls it brings, and how to keep numeric pipelines free of it.
1. Conversion Methods
// Object stream -> primitive stream (unboxing)
IntStream Stream<T>.mapToInt(ToIntFunction<? super T> f) // e.g. mapToInt(Integer::intValue)
LongStream Stream<T>.mapToLong(ToLongFunction<? super T> f)
DoubleStream Stream<T>.mapToDouble(ToDoubleFunction<? super T> f)
// Primitive stream -> object stream (boxing)
Stream<Integer> IntStream.boxed()
<U> Stream<U> IntStream.mapToObj(IntFunction<? extends U> f)
boxed() is equivalent to mapToObj(Integer::valueOf). Unboxing an Integer calls intValue(), which throws NullPointerException if the reference is null.
2. How Boxing Affects Streams
A Stream<Integer> holds references to Integer objects. Each arithmetic step unboxes the value, computes, and often boxes the result again. Integer.valueOf() reuses cached objects for values from -128 to 127, but larger values usually mean a new object per result, extra memory and extra work for the garbage collector.
Primitive streams avoid this by working on int, long and double directly. Their specialised methods, sum(), average(), max(), also need no comparator or collector.
List.3. Java Examples
Example 1: Converting between object and primitive streams (Java 9+)
Sum a list of boxed quantities with an IntStream, then build a list of doubled values.
import java.util.List;
import java.util.stream.Collectors;
public class BoxUnboxConversions {
public static void main(String[] args) {
List<Integer> quantities = List.of(12, 7, 30, 5);
int total = quantities.stream()
.mapToInt(Integer::intValue) // unbox once
.sum();
List<Integer> doubled = quantities.stream()
.mapToInt(Integer::intValue)
.map(q -> q * 2) // primitive arithmetic
.boxed() // box once, to collect
.collect(Collectors.toList());
System.out.println("Total: " + total);
System.out.println("Doubled: " + doubled);
}
}
Total: 54 Doubled: [24, 14, 60, 10]
How it works: The pipeline unboxes at the start, does all arithmetic on int values, and boxes only at the end, where a List requires objects.
Example 2: The same sum, boxed and unboxed
Sum one million numbers with reduce() on a boxed stream and with sum() on an IntStream.
import java.util.stream.IntStream;
public class BoxedVsPrimitiveSum {
public static void main(String[] args) {
long boxedSum = IntStream.rangeClosed(1, 1_000_000)
.boxed() // 1,000,000 Integer objects
.map(Integer::longValue) // and 1,000,000 Long objects
.reduce(0L, Long::sum);
long primitiveSum = IntStream.rangeClosed(1, 1_000_000)
.asLongStream()
.sum(); // no objects at all
System.out.println("Boxed: " + boxedSum);
System.out.println("Primitive: " + primitiveSum);
}
}
Boxed: 500000500000 Primitive: 500000500000
How it works: Both give the same answer, but the boxed version creates millions of wrapper objects (values above 127 are not cached) and the primitive version creates none. On large data the primitive pipeline is typically several times faster; measure with a proper benchmark tool such as JMH if it matters.
Example 3: Unboxing a null throws
A list of daily step counts has a missing day stored as null.
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class UnboxingNull {
public static void main(String[] args) {
List<Integer> steps = Arrays.asList(8200, null, 10450, 6900);
try {
steps.stream().mapToInt(Integer::intValue).sum();
} catch (NullPointerException e) {
System.out.println("Unboxing null: NullPointerException");
}
int safeTotal = steps.stream().filter(Objects::nonNull).mapToInt(Integer::intValue).sum();
System.out.println("Total without missing days: " + safeTotal);
}
}
Unboxing null: NullPointerException Total without missing days: 25550
How it works: Integer::intValue on a null reference throws. Filter nulls, or replace them with a default, before unboxing.
Example 4: Comparing boxed values
Compare Integer objects from a boxed stream with == and with equals().
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class BoxedIdentity {
public static void main(String[] args) {
List<Integer> small = Stream.of(100, 100).collect(Collectors.toList());
List<Integer> large = Stream.of(1000, 1000).collect(Collectors.toList());
System.out.println("100 == 100: " + (small.get(0) == small.get(1)));
System.out.println("1000 == 1000: " + (large.get(0) == large.get(1)));
System.out.println("1000 equals: " + large.get(0).equals(large.get(1)));
}
}
100 == 100: true 1000 == 1000: false 1000 equals: true
How it works: == compares object references. Values from -128 to 127 come from the Integer cache and share objects; 1000 does not, with default JVM settings. Always compare boxed values with equals() or unbox them first.
4. Real-World Use Cases
- Analytics on large data: keep sums and averages in primitive streams.
- APIs that need objects: box at the end to return a
List<Integer>or aMap. - Data cleaning: filter null wrapper values before unboxing.
5. Important Points
- Autoboxing is invisible in lambdas; check the stream type,
Stream<Integer>versusIntStream. - Null unboxing throws
NullPointerException. ==on wrappers compares references; useequals().- Collectors need objects: box before
collect(toList()). - Performance: boxing matters for large or frequently run pipelines; for a handful of values, clarity matters more.
6. Boxed vs Primitive Streams
| Operation | Boxed stream | Primitive stream |
|---|---|---|
| Sum | reduce(0, Integer::sum) or summingInt() | sum() |
| Maximum | max(Comparator.naturalOrder()) | max() |
| Average | collect(averagingInt(...)) | average() |
Collect to List | toList() | boxed().toList() |
Can hold null | Yes | No |
See IntStream, LongStream, DoubleStream for creating primitive streams.
7. Common Mistakes and Best Practices
Summing with reduce on wrappers
int total = orders.stream().map(Order::qty).reduce(0, Integer::sum); // boxes every quantity
int total = orders.stream().mapToInt(Order::qty).sum();
Boxing and unboxing back and forth
A pipeline such as boxed().map(x -> x * 2).mapToInt(Integer::intValue) boxes and unboxes for nothing. Keep the arithmetic in the primitive stream and box once at the end.
Other mistakes to avoid
- Comparing
Integervalues with==. - Unboxing data that may contain
null. - Using
Stream<Double>for numeric work instead ofDoubleStream.
8. Summary
mapToInt()and friends unbox into primitive streams;boxed()andmapToObj()box back.- Do arithmetic in primitive streams and box once, at the end.
- Unboxing
nullthrows; filter first. - Compare wrapper objects with
equals(), never==.
9. References
Frequently Asked Questions (FAQ)
Q1. What is boxing and unboxing in Java streams?
Boxing converts primitive values such as int into wrapper objects such as Integer, for example with IntStream.boxed(). Unboxing converts wrappers back into primitives, for example with mapToInt(Integer::intValue).
Q2. Why should I avoid boxing in streams?
Each boxed value is an object that costs memory and garbage-collection work, and arithmetic on wrappers unboxes and reboxes repeatedly. Primitive streams avoid this and offer sum(), average() and max() directly.
Q3. When do I need boxed()?
When the result must hold objects, for example to collect into a List<Integer>, use a Map, or call methods that only exist on Stream.
Q4. Why does mapToInt(Integer::intValue) throw NullPointerException?
Because one of the elements is null, and unboxing null is impossible. Filter with Objects::nonNull or replace nulls with a default before unboxing.
Q5. Why does == sometimes work for Integer values?
Integer.valueOf() caches values from -128 to 127, so equal small values share one object. Larger values are usually different objects, so == compares references and fails. Use equals().