If you want to convert a stream of primitives int, long, double to a stream of respective wrapper objects i.e. Integer, Long, Double then Java Stream API has a boxed() method to do this job.
boxed() method in Java
In Java stream API there are primitive specializations of Stream named IntStream, LongStream and DoubleStream and each of these interfaces has a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to an Integer, Long or Double respectively.
So, to summarize in java.util.stream.IntStream interface there is a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to an Integer.
In java.util.stream.LongStream interface there is a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to a Long.
In java.util.stream.DoubleStream interface there is a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to a Double.
boxed() is an intermediate operation.
boxed stream Java examples
1. If you have a Stream of ints that you want to collect to a List. It won’t be possible to directly store primitive integers into a list so you will get compile time error for the following lines of code.
IntStream intStream = IntStream.of(1, 2, 3, 4, 5); // Not able to collect primitives to a list intStream.collect(Collectors.toList());
In this scenario you can use boxed() to wrap primitive ints into Integer wrapper object which can than be stored into a List.
import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class StreamBoxedDemo { public static void main(String[] args) { IntStream intStream = IntStream.of(1, 2, 3, 4, 5); List<Integer> numList = intStream.boxed().collect(Collectors.toList()); System.out.println(numList); } }
Output
[1, 2, 3, 4, 5]
2. Using boxed() method of LongStream to get a Stream consisting of the elements of this stream, each boxed to a Long.
public class StreamBoxedDemo { public static void main(String[] args) { List<Long> numList = LongStream.of(1, 2, 3, 4, 5) .boxed().collect(Collectors.toList()); System.out.println(numList); } }
3. Using boxed() method of DoubleStream to get a Stream consisting of the elements of this stream, each boxed to a Double.
public class StreamBoxedDemo { public static void main(String[] args) { List<Double> numList = DoubleStream.of(1, 2, 3, 4, 5) .boxed().collect(Collectors.toList()); System.out.println(numList); } }
That's all for this topic Java Stream - boxed() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Advanced Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment