Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
  Signup/Sign In

How to Convert Stream to an Array in java

In this post, we are going to learn conversion of stream to an array. The stream is a sequence of elements that allows us to perform operations in a functional approach while the array is an object that stores a similar type of element.

Here, we have some examples where we are converting stream to an array of primitive values.

Time for an Example:

Let's create an example to convert the stream to an array. Here, we create a sequence of integers using rangeClosed() method of IntStream and then converted to an array using toArray() method.

import java.util.stream.IntStream;
public class Main {
	public static void main(String[] args){  
		IntStream integerStream = IntStream.rangeClosed(1, 5);
		// Convert stream into Array
		int[] arr = integerStream.toArray();
		for(int e:arr) {
			System.out.println(e);
		}		
	}
}


1
2
3
4
5

Time for another Example:

Let's take another example to get array from a stream. Here, we created a stream from a list and the converted using toArray() method by specifying type of array. In the other hand, we converted array to stream as well so that we can get elements in previous type if require.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Main {
	public static void main(String[] args){  
		Stream<String> stream = List.of("UK", "US", "BR").stream();
		// Convert string stream into string array
		String[] strArray = stream.toArray(String[]::new);
		for(String str : strArray) {
			System.out.println(str);
		}
		System.out.println("\nAfter conversion to array:");
		// Array to stream conversion
		Stream<String> stringStream = Arrays.stream(strArray);
		stringStream.forEach(System.out::println);

	}
}


UK
US
BR

After conversion to array:
UK
US
BR