00:00

Boxing and Unboxing in Java Streams

Last updated:

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

Stream.java and IntStream.java (API)
// 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.

Boxing and unboxing between stream types Row 1: a Stream of Integer becomes an IntStream with mapToInt Integer::intValue, which unboxes every element. Row 2: an IntStream becomes a Stream of Integer with boxed, which creates wrapper objects. Row 3: reduce with Integer::sum on a Stream of Integer unboxes and reboxes on every step. FROM METHOD TO Unboxing Stream<Integer> mapToInt(intValue) IntStream Boxing IntStream boxed() Stream<Integer> Both Stream<Integer> reduce(0, Integer::sum) Integer
Figure 1: Convert once at the boundary: unbox into a primitive stream for arithmetic, and box only when you need objects, such as for a 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.

BoxUnboxConversions.java
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);
    }
}
Output
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.

BoxedVsPrimitiveSum.java
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);
    }
}
Output
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.

UnboxingNull.java
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);
    }
}
Output
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().

BoxedIdentity.java
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)));
    }
}
Output
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 a Map.
  • Data cleaning: filter null wrapper values before unboxing.

5. Important Points

  • Autoboxing is invisible in lambdas; check the stream type, Stream<Integer> versus IntStream.
  • Null unboxing throws NullPointerException.
  • == on wrappers compares references; use equals().
  • 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

OperationBoxed streamPrimitive stream
Sumreduce(0, Integer::sum) or summingInt()sum()
Maximummax(Comparator.naturalOrder())max()
Averagecollect(averagingInt(...))average()
Collect to ListtoList()boxed().toList()
Can hold nullYesNo

See IntStream, LongStream, DoubleStream for creating primitive streams.

7. Common Mistakes and Best Practices

Summing with reduce on wrappers

Avoid
int total = orders.stream().map(Order::qty).reduce(0, Integer::sum);       // boxes every quantity
Prefer
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 Integer values with ==.
  • Unboxing data that may contain null.
  • Using Stream<Double> for numeric work instead of DoubleStream.

8. Summary

  • mapToInt() and friends unbox into primitive streams; boxed() and mapToObj() box back.
  • Do arithmetic in primitive streams and box once, at the end.
  • Unboxing null throws; filter first.
  • Compare wrapper objects with equals(), never ==.

9. References