DEV Community

Emmanuel Ogbinaka
Emmanuel Ogbinaka

Posted on

9 4

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).
[source][https://stackoverflow.com/a/47126809]

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 'java.util.stream.IntStream' cannot be applied to '(java.util.stream.Collector ?>,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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs