Core Java

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.

GitHub

IntStream api

IntStream examples

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.

Venkatesh Nukala

Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button