Java 8 – Stream to Array conversion using toArray() method

In this article, we will discuss Stream’s toArray() method in detail with examples

1. Stream toArray() method :

  • This Stream method is a terminal operation which reads given Stream and returns an Array containing all elements present in the Stream
  • The main purpose of this method is used to convert given Stream into an Array
  • If required, we can apply one/more intermediate operation before converting to an Array
  • If filters are applied to this Stream then resulting Array contains less number of elements than original Stream elements
  • There are 2 variants of toArray() method
    • Method signature 1 :- Object[] toArray()
    • Method signature 2 :- <T> T[] toArray(IntFunction<T[]> generator)



2. Stream toArray() method :

  • This is the first overloaded method which takes no-argument and returns an Object Array (Object[]) containing elements of Stream

2.1 Stream to Array conversion

  • First, we are going to convert Stream of Integers to Object[] Array
  • Next, a Stream contains Strings and we are going to convert to Object[] Array
  • Stream’s toArray() method allows us to convert Stream to Object[] only
  • If we need specific type then type-casting is required after conversion
  • Or else, we can use other overloaded toArray() method to convert Stream to an Array of specific type

StreamToArrayMethod.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class StreamToArrayMethod {

	public static void main(String[] args) {

		// 1. Stream of Integers
		Stream<Integer> integerStream = Stream.of(1,2,3,4,5);

		// 1.1 conversion of Stream to Object Array
		Object[] intArray = integerStream.toArray();

		// 1.2 print to console
		System.out.println("Conversion of Stream of Integer"
				+ " to Object[] Array :- \n" 
				+ Arrays.toString(intArray));

		// 2. Stream of Strings
		Stream<String> stringStream = Stream.of(
				"Test", "ODI", "T20", 
				"IPL", "CPL", "BBL"
				);

		// 2.1 conversion of Stream to Object Array
		Object[] strArray = stringStream.toArray();

		// 2.2 print to console
		System.out.println("\nConversion of Stream of String"
				+ " to Object[] Array :- \n" 
				+ Arrays.toString(strArray));
	}
}

Output:

Conversion of Stream of Integer to Object[] Array :- 
[1, 2, 3, 4, 5]

Conversion of Stream of String to Object[] Array :- 
[Test, ODI, T20, IPL, CPL, BBL]

3. <T> T[] toArray(IntFunction<T[]> generator):

  • This is the second overloaded method which takes generator IntFunction as argument
  • The generator Function takes an integer which is the size of the desired array, and produces an array of the desired size
  • We are going convert Stream to an Array using below approach,
    1. Method/Constructor Reference
    2. Lambda Expression
    3. Customized IntFunction

3.1 Method/Constructor Reference

  • First, we are going to convert Stream of Integers to Integer[] Array using Constructor Reference
  • Similarly, a Stream contains Strings and we are going to convert to String[] Array

StreamToArrayUsingConstructorReference.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class StreamToArrayUsingConstructorReference {

	public static void main(String[] args) {

		// 1. Stream of Integers
		Stream<Integer> integerStream = Stream.of(1,2,3,4,5);

		// 1.1 conversion of Integer Stream to Integer[] Array
		Integer[] intArray = integerStream.toArray(Integer[]::new);

		// 1.2 print to console
		System.out.println("Conversion of Stream of Integer"
				+ " to Integer[] Array :- \n" 
				+ Arrays.toString(intArray));

		// 2. Stream of Strings
		Stream<String> stringStream = Stream.of(
				"Test", "ODI", "T20", 
				"IPL", "CPL", "BBL"
				);

		// 2.1 conversion of String Stream to String[] Array
		String[] strArray = stringStream.toArray(String[]::new);

		// 2.2 print to console
		System.out.println("\nConversion of Stream of String"
				+ " to String[] Array :- \n" 
				+ Arrays.toString(strArray));
	}
}

Output:

Conversion of Stream of Integer to Integer[] Array :- 
[1, 2, 3, 4, 5]

Conversion of Stream of String to String[] Array :- 
[Test, ODI, T20, IPL, CPL, BBL]

3.2 Lambda Expression

  • First, we are going to convert Stream of Integer to Integer[] Array using Lambda Expression
  • Similarly, a Stream contains Strings and we are going to convert to String[] Array

StreamToArrayUsingLambdaExpression.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class StreamToArrayUsingLambdaExpression {

	public static void main(String[] args) {

		// 1. Stream of Integers
		Stream<Integer> integerStream = Stream.of(1,2,3,4,5);

		// 1.1 conversion of Integer Stream to Integer[] Array
		Integer[] intArray = integerStream.toArray(size -> new Integer[size]);

		// 1.2 print to console
		System.out.println("Conversion of Stream of Integer"
				+ " to Integer[] Array using Lambda :- \n" 
				+ Arrays.toString(intArray));

		// 2. Stream of Strings
		Stream<String> stringStream = Stream.of(
				"Test", "ODI", "T20", 
				"IPL", "CPL", "BBL"
				);

		// 2.1 conversion of String Stream to String[] Array
		String[] strArray = stringStream.toArray(size -> new String[size]);

		// 2.2 print to console
		System.out.println("\nConversion of Stream of String"
				+ " to String[] Array using Lambda :- \n" 
				+ Arrays.toString(strArray));
	}
}

Output:

Conversion of Stream of Integer to Integer[] Array using Lambda :- 
[1, 2, 3, 4, 5]

Conversion of Stream of String to String[] Array using Lambda :- 
[Test, ODI, T20, IPL, CPL, BBL]

3.3 Customized IntFunction

  • We have created new class implementing IntFucntion functional interface specifically for type String[] array
  • Now for conversion, we need to pass instance of this class to toArray() method as argument
  • A Stream contains Strings and we are going to convert to String[] Array passing this instance as argument

CustomIntFunction.java

package net.bench.resources.stream.toarray.example;

import java.util.function.IntFunction;

public class CustomIntFucntion implements IntFunction<String[]>{

	@Override
	public String[] apply(int size) {
		return new String[size];
	}
}

CustomIntFunction.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class StreamToArrayUsingCustomIntFunction {

	public static void main(String[] args) {

		// 1. Stream of Strings
		Stream<String> stringStream = Stream.of(
				"Test", "ODI", "T20", 
				"IPL", "CPL", "BBL"
				);

		// 1.1 String Stream to String[] Array using custom IntFunction
		String[] strArray = stringStream.toArray(new CustomIntFucntion());

		// 1.2 print to console
		System.out.println("Conversion of Stream of String"
				+ " to String[] Array using Custom IntFucntion :- \n" 
				+ Arrays.toString(strArray));
	}
}

Output:

Conversion of Stream of String to String[] Array using Custom IntFucntion :- 
[Test, ODI, T20, IPL, CPL, BBL]

4. Working with primitive-types and Wrapper classes :

  • We can directly convert Stream to an Array of primitive-types or Wrapper classes
  • For Stream to Wrapper class Array conversion, we can use either Method/constructor reference or Lambda expression
  • For Stream to Primitive-type Array conversion, we can use mapToInt(), mapToLong() or mapToDouble() methods based on the primitive-types we are expecting in the result

4.1 Stream to Wrapper class Array conversion

  • First, we are converting Stream of Integer to Integer[] array using Constructor Reference
  • Second, we are converting Stream of Long to Long[] array using Lambda Expression
  • Third, we are converting Stream of Double to Double[] array using Constructor Reference

StreamToWrapperArrayConversion.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class StreamToWrapperArrayConversion {

	public static void main(String[] args) {

		// 1. Stream of Integers
		Stream<Integer> integerStream = Stream.of(1,2,3,4,5);

		// 1.1 Stream to Array using Constructor Reference
		Integer[] intArrayCR = integerStream.toArray(Integer[]::new);
		System.out.println("1. Integer Stream to Integer[] array "
				+ "using Constrcutor Reference :- \n" 
				+ Arrays.toString(intArrayCR));


		// 2. Stream of Long
		Stream<Long> longStream = Stream.of(100L, 200L, 300L, 400L, 500L);

		// 2.1 Stream to Array using Lambda Expression
		Long[] lngArrayLEx = longStream.toArray(size -> new Long[size]);
		System.out.println("\n2. Long Stream to Long[] array "
				+ "using Lambda Expression :- \n"  
				+ Arrays.toString(lngArrayLEx));


		// 3. Stream of Double
		Stream<Double> doubleStream = Stream.of(100.2, 200.3, 300.4, 400.5, 500.6);

		// 3.1 Stream to Array using Constructor Reference
		Double[] dblArrayLEx = doubleStream.toArray(Double[]::new);
		System.out.println("\n3. Double Stream to Double[] array "
				+ "using Constrcutor Reference :- \n"  
				+ Arrays.toString(dblArrayLEx));
	}
}

Output:

1. Integer Stream to Integer[] array using Constrcutor Reference :- 
[1, 2, 3, 4, 5]

2. Long Stream to Long[] array using Lambda Expression :- 
[100, 200, 300, 400, 500]

3. Double Stream to Double[] array using Constrcutor Reference :- 
[100.2, 200.3, 300.4, 400.5, 500.6]

4.2 Stream to Primitive-type Array conversion

  • First, we are converting Stream of Integer to primitive int[] array using mapToInt() method
  • Second, we are converting Stream of Long to primitive long[] array using mapToLong() method
  • Third, we are converting Stream of Double to primitive double[] array using mapToDouble() method

StreamToPrimitiveArrayConversion.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.Stream;

public class StreamToPrimitiveArrayConversion {

	public static void main(String[] args) {

		// 1. Stream of Integers
		Stream<Integer> integerStream = Stream.of(1,2,3,4,5);

		// 1.1 Stream to primitive int[] Array using mapToInt()
		int[] intArrayCR = integerStream.mapToInt(i -> i).toArray();
		System.out.println("1. Integer Stream to primitive int[] array "
				+ "using mapToInt() :- \n" 
				+ Arrays.toString(intArrayCR));


		// 2. Stream of Long
		Stream<Long> longStream = Stream.of(100L, 200L, 300L, 400L, 500L);

		// 2.1 Stream to primitive long[] Array using mapToLong()
		long[] lngArrayLEx = longStream.mapToLong(l -> l).toArray();
		System.out.println("\n2. Long Stream to primitive long[] array "
				+ "using mapToLong() :- \n"  
				+ Arrays.toString(lngArrayLEx));


		// 3. Stream of Double
		Stream<Double> doubleStream = Stream.of(100.2, 200.3, 300.4, 400.5, 500.6);

		// 3.1 Stream to primitive double[] Array using mapToDouble()
		double[] dblArrayLEx = doubleStream.mapToDouble(d -> d).toArray();
		System.out.println("\n3. Double Stream to primitive double[] array "
				+ "using mapToDouble() :- \n"  
				+ Arrays.toString(dblArrayLEx));
	}
}

Output:

1. Integer Stream to primitive int[] array using mapToInt() :- 
[1, 2, 3, 4, 5]

2. Long Stream to primitive long[] array using mapToLong() :- 
[100, 200, 300, 400, 500]

3. Double Stream to primitive double[] array using mapToDouble() :- 
[100.2, 200.3, 300.4, 400.5, 500.6]

5. Conversion of Infinite Stream to an Array :

  • We can generate Integer stream, Long stream or Double stream using IntStream, LongStream or DoubleStream respectively but make sure to limit them using limit() method of Stream
  • Then we can easily convert infinite stream to an Array using toArray() method
  • Arrays to Stream conversion is possible for both primitive-types and Wrapper-types

5.1 IntStream conversion to an Array

  • First, generate odd integer stream using IntStream starting from 1 limiting to 10 integer numbers and then convert to primitive int[] Array using toArray() method
  • Second, generate numbers between 1 and 7 using rangeClosed() method of IntStream and then convert to wrapper Integer[] Array using constructor reference (i.e.; toArray(Integer[]::new) method)

IntStreamConversion.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.IntStream;

public class IntStreamConversion {

	public static void main(String[] args) {

		// 1. odd - generate IntStream with limit
		IntStream intStreamOdd = IntStream.iterate(1, i -> i + 2);

		// 1.1 IntStream to primitive int[] array
		int[] intArray = intStreamOdd
				.limit(10) // limit to 10 ODD integers
				.toArray();

		System.out.println("1. IntStream to primitive int[] array :- "
				+ Arrays.toString(intArray));

		// 2. IntStream to Integer[] array
		Integer[] intArrayBoxed = IntStream
				.rangeClosed(1, 7) // range 1-7
				.boxed() // boxed to Wrapper-type
				.toArray(Integer[]::new);

		System.out.println("\n2. IntStream to Wrapper Integer[] array :- "
				+ Arrays.toString(intArrayBoxed));
	}
}

Output:

1. IntStream to primitive int[] array :- [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

2. IntStream to Wrapper Integer[] array :- [1, 2, 3, 4, 5, 6, 7]

5.2 LongStream conversion to an Array

  • First, generate long stream using LongStream of 5 long numbers and then convert to primitive long[] Array using toArray() method
  • Second, generate long numbers between 10 and 17 using rangeClosed() method of LongStream and then convert to wrapper Long[] Array using constructor reference (i.e.; toArray(Long[]::new) method)

LongStreamConversion.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.LongStream;

public class LongStreamConversion {

	public static void main(String[] args) {

		// 1. odd - generate LongStream with limit
		LongStream lngStream = LongStream.iterate(100L, i -> i + 100L);

		// 1.1 LongStream to primitive long[] array
		long[] lngArray = lngStream
				.limit(5) // limit to 7 long numbers
				.toArray();

		System.out.println("1. LongStream to primitive long[] array :- "
				+ Arrays.toString(lngArray));

		// 2. LongStream to Long[] array
		Long[] lngArrayBoxed = LongStream
				.rangeClosed(10L, 17L) // range 1-7
				.boxed() // boxed to Wrapper-type
				.toArray(Long[]::new);

		System.out.println("\n2. LongStream to Wrapper Long[] array :- "
				+ Arrays.toString(lngArrayBoxed));
	}
}

Output:

1. LongStream to primitive long[] array :- [100, 200, 300, 400, 500]

2. LongStream to Wrapper Long[] array :- [10, 11, 12, 13, 14, 15, 16, 17]

5.3 DoubleStream conversion to an Array

  • First, generate double stream using DoubleStream of 5 double numbers and then convert to primitive double[] Array using toArray() method
  • Provide double values to of() method of DoubleStream and then convert to wrapper Double[] Array using constructor reference (i.e.; toArray(Double[]::new) method)

DoubleStreamConversion.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.stream.DoubleStream;

public class DoubleStreamConversion {

	public static void main(String[] args) {

		// 1. generate DoubleStream with limit
		DoubleStream dblStream = DoubleStream.iterate(10.5, l -> l + 10.0);

		// 1.1 DoubleStream to primitive double[] array
		double[] dblArray = dblStream
				.limit(5) // limit to 5 long nu	mbers
				.toArray();

		System.out.println("1. DoubleStream to primitive double[] array :- "
				+ Arrays.toString(dblArray));

		// 2. DoubleStream to Double[] array
		Double[] dblArrayBoxed = DoubleStream
				.of(6.44, 3.45, 6.43, 3.34, 5.15)
				.boxed() // boxed to Wrapper-type
				.toArray(Double[]::new);

		System.out.println("\n2. DoubleStream to Wrapper Double[] array :- "
				+ Arrays.toString(dblArrayBoxed));

	}
}

Output:

1. DoubleStream to primitive double[] array :- [10.5, 20.5, 30.5, 40.5, 50.5]

2. DoubleStream to Wrapper Double[] array :- [6.44, 3.45, 6.43, 3.34, 5.15]

6. Collect to an Array after filtering/mapping :

  • We can apply one or more intermediate operations to a Stream for processing before converting to an Array
  • While filtering, there is a possibility that number of elements in the converted array is less than the original Stream elements
  • But while mapping, there will be no reduction in the number of elements in the original Stream and converted Array

Student.java

package net.bench.resources.stream.toarray.example;

public class Student {

	// member variables
	private int rollNumber;
	private String name;
	private int age;

	// 3-arg parameterized constructors

	// getters & setters

	// toString()
}

6.1 Filter a Stream and then convert to an Array

  • A list contains 5 Student information with attributes like Id, Name and their Age
  • We are filtering Students on the basis of their age who are under 20 and then storing into Array using Constructor Reference (i.e.; toArray(Student[]::new) method)

FilterAndConvertToArray.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.List;

public class FilterAndConvertToArray {

	public static void main(String[] args) {

		// list of students
		List<Student> students = Arrays.asList(
				new Student(1, "Viraj", 17),
				new Student(2, "Krishnanand", 18),
				new Student(3, "Rishi", 16),
				new Student(4, "Suresh", 23),
				new Student(5, "Aditya", 21)
				);

		// print original Student list
		System.out.println("Original Student list :- \n");
		students.stream().forEach(System.out::println);

		// filter Student age less than 20 and store it in Array
		Student[] studentArray = students
				.stream()
				.filter(student -> student.getAge() < 20)
				.toArray(Student[]::new);

		// print to console
		System.out.println("\nStudents with age less-than 20 :- \n"
				+ Arrays.toString(studentArray));
	}
}

Output:

Original Student list :- 

Student [rollNumber=1, name=Viraj, age=17]
Student [rollNumber=2, name=Krishnanand, age=18]
Student [rollNumber=3, name=Rishi, age=16]
Student [rollNumber=4, name=Suresh, age=23]
Student [rollNumber=5, name=Aditya, age=21]

Students with age less-than 20 :- 
[
Student [rollNumber=1, name=Viraj, age=17], 
Student [rollNumber=2, name=Krishnanand, age=18], 
Student [rollNumber=3, name=Rishi, age=16]
]

6.2 Map a Stream and then convert to an Array

  • A list contains 5 Student information with attributes like Id, Name and Age
  • We are extracting/mapping Student’s name to upper case and then stroing into Array using Constructor Reference (i.e.; toArray(String[]::new) method)

MapAndConvertToArray.java

package net.bench.resources.stream.toarray.example;

import java.util.Arrays;
import java.util.List;

public class MapAndConvertToArray {

	public static void main(String[] args) {

		// list of students
		List<Student> students = Arrays.asList(
				new Student(1, "Viraj", 17),
				new Student(2, "Krishnanand", 18),
				new Student(3, "Rishi", 16),
				new Student(4, "Suresh", 23),
				new Student(5, "Aditya", 21)
				);

		// print original Student list
		System.out.println("Original Student list :- \n");
		students.stream().forEach(System.out::println);

		// Map Student name to upper case and store it in Array
		Student[] studentArray = students
				.stream()
				.map(student -> new Student(
						student.getRollId(), 
						student.getName().toUpperCase(), 
						student.getAge()
						))
				.toArray(Student[]::new);

		// print to console
		System.out.println("\nStudents name in Upper Case :- \n"
				+ Arrays.toString(studentArray));

	}
}

Output:

Original Student list :- 

Student [rollNumber=1, name=Viraj, age=17]
Student [rollNumber=2, name=Krishnanand, age=18]
Student [rollNumber=3, name=Rishi, age=16]
Student [rollNumber=4, name=Suresh, age=23]
Student [rollNumber=5, name=Aditya, age=21]

Students name in Upper Case :- 
[
Student [rollNumber=1, name=VIRAJ, age=17], 
Student [rollNumber=2, name=KRISHNANAND, age=18], 
Student [rollNumber=3, name=RISHI, age=16], 
Student [rollNumber=4, name=SURESH, age=23], 
Student [rollNumber=5, name=ADITYA, age=21]
]

7. Array to Stream conversion :

  • There are 2 methods available in Java 8 namely Arrays.stream() and Stream.of()
  • Both these methods return Stream
  • Using above methods, we can easily convert Array to Stream
  • Once after converting Array to Stream we can apply one/more intermediate operation to play with Stream to get the desired result
  • Read Array to Stream for examples along with explanation

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - Array to Stream conversion
Java 8 - Stream concat() method for merging elements