Java 8 – Convert IntStream to Array
A quick guide on how to convert IntSteam to Array in java 8.
1. Overview
In this tutorial, We’ll learn how to convert IntStream to Array of ints in java 8.
IntStream is used to create infinite streams with the number series pattern.
But, some of the time we might need to convert the number series to an array.
2. Java 8 – Convert IntStream to Array
Let us take the example to generate the first 100 odd numbers from IntStream and collect them into an array of integers.
Example
After creating the IntStream, we need to take the first 100 values from it using limit(100) function. Then use the collect terminal operation using toArray() method. toArray() method converts the intermediate stream into inteter array.
package com.javaprogramto.java8.intstream.toarray; import java.util.stream.IntStream; public class IntStreamToArrayExample { public static void main(String[] args) { IntStream oddNumbers = IntStream.iterate(1, i -> i +2); int[] oddArray = oddNumbers.limit(100).toArray(); System.out.println("Odd array length - "+oddArray.length); } }
Output
Odd array length - 100
3. Conclusion
In this article, we’ve seen how to convert int stream into an array of integer values in java 8.
Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Java 8 – Convert IntStream to Array Opinions expressed by Java Code Geeks contributors are their own. |