DEV Community

Emmanuel Ogbinaka
Emmanuel Ogbinaka

Posted on

The Java `.boxed()` Method

In this post I'll be talking about the boxed() method of Java streams.

What is the boxed() method?

The method boxed() is designed only for streams of some primitive types (IntStream, DoubleStream, and LongStream) to box each primitive value of the stream into the corresponding wrapper class (Integer, Double, and Long respectively).

what this means is that whenever we use any of the primitive generators the generated values are corresponding primitives to the stream. that is :

IntStream - int
LongStream - long
DoubleStream - double

Although, we can perform intermediary operations on the generated values but we cannot perform some terminal operations on the generated values.

for example,
Generate a list of numbers from 1 to 100.

List<Integer> numbers = IntStream.rangeClosed(1 , 100).collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode

The above operation will throw a compile time exception of
_ java.util.function.BiConsumer )' in '' cannot be applied to '( ?>,java.util.List >)'_

This is where the .boxed() method comes in.
Notice the generic List uses the wrapper class for the primitive int type. What the .boxed() method does is that it returns a Stream consisting of the elements of the given stream, each boxed to an object of the corresponding wrapper class.

Or simply put, the .boxed() method puts each value in the stream in its corresponding wrapper class.

IntStream.boxed() - Integer
LongStream.boxed() - Long
DoubleStream.boxed() - Double

So a good solution to the example problem is:

List<Integer> numbers = IntStream.rangeClosed(1 , 100).boxed().collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode

Hope you find this info useful. Thanks.

Latest comments (0)