January 18, 2024

Java Stream boxed() With Examples

The boxed() method in Java Stream is used to wrap the primitive value (int, long or double) to its respective wrapper class object.

There are primitive specializations of Stream named IntStream, LongStream and DoubleStream each of these interfaces have a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to an Integer, Long or Double respectively. Note that boxed() is an intermediate operation.

boxed stream Java examples

Let’s see few examples how to box a primitive value into its wrapper class using boxed() method.

1. boxed() in IntStream which is used to get a Stream consisting of the elements of this stream, each boxed to an Integer.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class BoxedIntStream {
  public static void main(String[] args) {    
    Stream<Integer> wrappedInts = IntStream.of(1, 2, 3, 4, 5).boxed();
    List<Integer> numList = wrappedInts.collect(Collectors.toList());
    System.out.println(numList);
  }
}
Output
[1, 2, 3, 4, 5]

Here IntStream having int elements first uses boxed() method to wrap these primitive ints into an object of Integer class and then use the Stream consisting of those Integer objects to convert into a List. Doing it directly won’t work, so the following statement results in compile time error.

List<Integer> numList = IntStream.of(1,2,3,4,5).collect(Collectors.toList());

2. boxed() in LongStream which is used to get a Stream consisting of the elements of this stream, each boxed to a Long.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

public class BoxedLongStream {
  public static void main(String[] args) {
    List<Long> numList = LongStream.of(6, 7, 8, 9, 10)
          .boxed()
          .collect(Collectors.toList());
    System.out.println(numList);
  }
}
Output
[6, 7, 8, 9, 10]

3. boxed() in DoubleStream which is used to get a Stream consisting of the elements of this stream, each boxed to a Double.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;

public class BoxedDoubleStream {
  public static void main(String[] args) {
    List<Double> numList = DoubleStream.of(6, 7, 8, 9, 10)
                               .boxed()
                               .collect(Collectors.toList());
    System.out.println(numList);

  }
}
Output
[6.0, 7.0, 8.0, 9.0, 10.0]

That's all for the topic Java Stream boxed() With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment