IntStream boxed() in Java
IntStream boxed() is a method provided by the IntStream interface in Java, which returns a Stream in which each element of the IntStream is boxed into an Integer.
Note: Intstream boxed() is an intermediate operation that is invoked on a stream object and returns another stream object after processing, allows for further operations to chain together. Usually, these operations do not execute any processing until a terminal operation is called.
Syntax:
Stream
Parameters:
- It accepts a Stream to support sequential and parallel aggregate operations.
- An Integer, which wraps a value of the primitive int values into objects.
Return value: The method returns a stream that has been boxed to an integer.
Example 1:
The example illustrates how to use IntStream and its boxed() method to convert primitive int values into a stream of Integer objects. We create an IntStream, then convert it into a Stream
FileName: IntStreamBoxedExample.java
// importing util packages. import java.util.*; // importing Stream and IntStream classes from java.util.stream package import java.util.stream.Stream; import java.util.stream.IntStream; public class IntStreamBoxedExample { // main method public static void main(String[] args) { // Creating an IntStream with elements from 2 to 10 IntStream intStrm = IntStream.range(2, 10); // using IntStream boxed() to convert each element of IntStream to StreamStream boxedStrm = intStrm.boxed(); // displaying the elements of boxedStream boxedStrm.forEach(System.out::println); } }
Output:
2 3 4 5 6 7 8 9
Example 2:
The Use of IntStream and its boxed() method to convert int values into a stream of Integer objects is demonstrated in the below example. We are creating an IntStream, using the boxed() method, converting IntStream into a Stream
FileName: IntStreamBoxedExample.java
// importing util packages. import java.util.*; // importing Stream and IntStream classes from java.util.stream package import java.util.stream.Stream; import java.util.stream.IntStream; public class IntStreamBoxedExample { // main method public static void main(String[] args) { // creating an IntStream with elements from 2 to 10 IntStream intStrm = IntStream.range(2, 10); // using IntStream boxed() to convert each element of IntStream to StreamStream boxedStrm = intStrm.boxed(); // combining the boxed stream with another Stream containing strings Stream
Output:
2 3 4 5 6 7 8 9 Tutorials and Examples