Convert Java Stream to Array

By Arvind Rai, June 10, 2020
On this page we will learn how to convert Java Stream into Array. The best way to convert is using Stream.toArray(IntFunction) method. In our examples we will convert Java Stream into Array in following ways.

1. We will use Stream.toArray(IntFunction) which will return the array of the desired type.

2. Using Stream.toArray() method which will return Object[] and then we change it into required datatype.

3. For integer stream we can use IntStream.toArray() that will return int[]. In the same way we can use LongStream.toArray() to get long[] and DoubleStream.toArray() to get double[].

4. We can convert stream into list and then list into array. To convert stream into list we need to use collect(Collectors.toList()) on the stream and to convert list into array we can use List.toArray method.

1. Using Stream.toArray(IntFunction)

The toArray(IntFunction) method returns an array containing the elements of this stream using the provided generator as IntFunction. This method is terminal operation.
A[] toArray(IntFunction<A[]> generator) 
Parameters: Pass a generator as IntFunction which produces a new array of the desired type and the provided length.
Returns: The method returns an array consisting the elements of stream.
Throws: The method throws ArrayStoreException if the runtime type of any element of this stream is not assignable to the runtime component type of the generated array.

Example-1:
In this example we will convert stream of string into array of string.
List<String> list = Arrays.asList("A", "B", "C", "D");
String[] strArray = list.stream().toArray(String[]::new);
for(String s : strArray) {
  System.out.println(s);
} 
The output will be A B C D. In the above example we have instantiated IntFunction as generator in toArray method using method reference.
Now find the example with lambda expression.
String[] strArray = list.stream().toArray(size -> new String[size]); 
Find one more example.
StreamToStringArray.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
public class StreamToStringArray {
  public static void main(String[] args) {
     List<String> list = Arrays.asList("Krishna", "Mahesh", "Kush");
     String[] strArray = list.stream()
    	 .filter(e -> e.startsWith("K"))
    	 .toArray(size -> new String[size]);
     for(String s : strArray) {
       System.out.println(s);
     }
  }
} 
Output
Krishna
Kush 

Example-2:
In this example we will convert stream of integer into array of integer.
StreamToIntegerArray.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
public class StreamToIntegerArray {
  public static void main(String[] args) {
     List<Integer> list = Arrays.asList(10, 20, 30, 40);
     Integer[] intArray = list.stream()
    	 .map(e -> e * 2)
    	 .toArray(Integer[]::new);
     for(Integer i : intArray) {
       System.out.println(i);
     }
  }
} 
The output will be 20 40 60 80.
In the above example we have used method reference. Now find the code with lambda expression.
List<Integer> list = Arrays.asList(10, 20, 30, 40);
Integer[] intArray = list.stream()
  .map(e -> e * 2)
  .toArray(size -> new Integer[size]); 

2. Using Stream.toArray()

The toArray() method returns an Object array containing the elements of this stream.
Object[] toArray() 
This method is terminal operation.

Example-1: In this example we will convert a stream of string into array of string. We know that toArray() returns Object[], so to convert it in our required datatype, we can use Arrays.copyOf method.
Object[] objArray = Stream.of("AA", "BB", "CC").toArray();
String[] stArray = Arrays.copyOf(objArray, objArray.length, String[].class);

for(String s : stArray) {
  System.out.println(s);
} 
The output will be AA BB CC.

Example-2: In this example we will convert stream of integer into array of integer.
Object[] objArray = Stream.of(10, 20, 30, 40).toArray();
Integer[] intArray = Arrays.copyOf(objArray, objArray.length, Integer[].class);

for(Integer i : intArray) {
  System.out.println(i);
} 
The output will be 10 20 30 40.

3. Using IntStream.toArray()

The IntStream is the stream of int-valued elements. The IntStream.toArray() method converts stream of int values into the int array.
int[] toArray() 
We can get IntStream object in following ways.
1.
IntStream intStream = IntStream.of(1,2,3,4,5); 
2.
IntStream intStream = IntStream.rangeClosed(1, 5); 
3.
IntStream intStream = Stream.of(4,5,6,7,8).mapToInt(i -> i); 

Now let us discuss some examples to use IntStream.toArray() method.

Example-1:
int[] intArray = IntStream.of(10, 20, 30, 40).toArray();
for(Integer i : intArray) {
  System.out.println(i);
} 
The output is 10 20 30 40.
Example-2:
int[] intArray = IntStream.rangeClosed(10, 15).toArray();
for(Integer i : intArray) {
  System.out.println(i);
} 
The output is 10 11 12 13 14 15.
Example-3:
int[] intArray = Stream.of(3,4,5,6).mapToInt(i -> i * 2).toArray();
for(Integer i : intArray) {
  System.out.println(i);
} 
The output is 6 8 10 12.

4. Using Collectors.toList()

We can convert stream into list and then convert list into array. To convert stream into list we need to use collect(Collectors.toList()) on the stream. To convert list into array we can use List.toArray method.
StreamToListToArray.java
package com.concretepage;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamToListToArray {
  public static void main(String[] args) {
	System.out.println("--- For String ---");
	String[] ar = Stream.of("Java", "Angular", "Spring")
		.collect(Collectors.toList())
		.toArray(new String[0]);
	
	for(String e : ar) {
	    System.out.println(e);	  
	}
	
	System.out.println("--- For Integer ---");
	Integer[] intArray = Stream.of(15, 20, 30)
		.map(e -> e * 2)
		.collect(Collectors.toList())
		.toArray(new Integer[0]);
	
        for(Integer i : intArray) {
            System.out.println(i);
        }	
  }
} 
Output
--- For String ---
Java
Angular
Spring
--- For Integer ---
30
40
60 

5. Reference

Java doc: Stream
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us