Sunday, August 11, 2019

Java 8 IntStream boxed() Method Example

1. Overview

In this tutorial, We'll learn about the new java 8 IntStream API boxed() method.

IntStream boxed() returns a Stream consisting of the elements of this stream, each boxed to an Integer. That means to convert all primitive int values to wrapper Integer type objects Stream.

This is part of Java.util.IntStream API course.

Note: This method is part of Intermediate Operations. All these are invoked lazy and executed upon terminal operations invocation.

Terminal opeartions such as forEach(), forEachOrdered(), iterator() etc.



2. boxed() method

Syntax:

Stream<integer> boxed()

This returns a Stream which is a type of Integer.

Example:

Example program to covert IntStream to Stream<integer>.

package com.java.w3schools.blog.java8.stream.intstream;

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

/**
 * 
 * Java 8 IntStream boxed() Method Example
 * 
 * @author venkateshn
 *
 */
public class BoxedExample {

 public static void main(String[] args) {

  // Creating a IntStream from values 10 to 14. End index is exlusive.
  IntStream intStream = IntStream.range(10, 15);
  
  // calling boxed() method on intStream
  Stream<Integer> streamInt = intStream.boxed();
  
  streamInt.forEach( value -> System.out.println(value));
 }

}


Output:

10
11
12
13
14

Here first created int stream using range(startInclusive, endExclusive) method which is also part of IntStream API. Next, invoked boxed() method to convert it into Stream<integer>.

3. boxed() using iterator() method of Stream


In the above example, forEach is used to print the values of converted Stream<integer>. The same can be rewritten using Method Reference.

streamInt.forEach(System.out::println);

If we add this directly in the above program in section 2 without any change then it may throw "java.lang.IllegalStateException: stream has already been operated upon or closed".

So, First, comment on the forEach consumer line then add this line. If you run the code now, it will not throw any exception and executes with no errors.

Now, coming to the how to use iterator() on returned stream.


ntStream evenNmbers = IntStream.of(2, 4, 6, 8, 10);
Stream<Integer> evenStream = evenNmbers.boxed();

Iterator<Integer> integerValues = evenStream.iterator();
integerValues.forEachRemaining(value -> System.out.println("Even Number : " + value));

Output:

Even Number : 2
Even Number : 4
Even Number : 6
Even Number : 8
Even Number : 10

4. Conclusion

In this article, We've seen when to use boxed() method from IntStream API. This is mainly to convert primitive values to Stream<integer>

Seen examples how to consumer the returned Stream<integer> using forEach() and iterator().


As usual, the examples shown are over GitHub.
API Ref

No comments:

Post a Comment