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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more