Java Stream toArray() Example

Learn to convert stream to array using Stream.toArray() API. This post contains multiple examples for collecting stream elements to array under different usecases.

Convert stream to array

Java 8 Stream.toArray() method is used to convert a stream into an array. In other words, toArray() accumulates the stream elements and returns them as an array.

In this tutorial, we will see multiple examples for collecting the Stream elements into an array.

1. Stream toArray() Method

The toArray() method returns an array containing the elements of the given stream. This is a terminal operation. It has two main variations:

Object[] toArray()
<T> T[]  toArray(IntFunction<T[]> generator)
  • The first method collects the elements of the stream into an array of Object.
  • The second method uses a generator function to produce a new array of the desired type and the provided length.

When working with parallel streams, the order of elements in the resulting array may not be predictable.

2. Stream toArray() Example

Example 1: Converting ‘Stream<String>‘ to ‘String[]

In the given example, we are converting a stream to an array using using toArray() API. It uses the String[]::new generator function for creating a new array of type String. This is equivalent to writing a lambda expression that creates a new String array, such as ‘size -> new String[size]‘.

Stream<String> tokenStream = Stream.of("A", "B", "C", "D");
     
String[] tokenArray = tokenStream.toArray(String[]::new);
 
//Verification
System.out.println( Arrays.toString(tokenArray) );  

Program output.

[A, B, C, D]

Example 2: Converting Infinite Stream to Array

To convert an infinite stream into an array, we must limit the stream to a finite number of elements.

Infinite Stream of Integers

IntStream infiniteNumberStream = IntStream.iterate(1, i -> i+1);
     
int[] intArray = infiniteNumberStream.limit(10).toArray();  // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Infinite boxed stream of Integers

IntStream infiniteNumberStream = IntStream.iterate(1, i -> i+1);
 
Integer[] integerArray = infiniteNumberStream.limit(10)
          .boxed()
          .toArray(Integer[]::new);  // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 3: Stream, filter, and collect to an Array

Sometimes we need to find specific items in the stream and then add only those elements to the array. Here, we can use Stream.filter() method to pass a predicate that will return only those elements that match the pre-condition.

List<Employee> employeeList = new ArrayList<>(Arrays.asList(
      new Employee(1, "A", 100),
      new Employee(2, "B", 200),
      new Employee(3, "C", 300),
      new Employee(4, "D", 400),
      new Employee(5, "E", 500),
      new Employee(6, "F", 600)));

Employee[] employeesArray = employeeList.stream()
    .filter(e -> e.getSalary() < 400)
    .toArray(Employee[]::new);

System.out.println(Arrays.toString(employeesArray));

Program output.

[Employee [id=1, name=A, salary=100.0],
Employee [id=2, name=B, salary=200.0],
Employee [id=3, name=C, salary=300.0]]

3. Summary

The Stream.toArray() method converts a stream into an array. The default toArray() returns an array of Object and the parameterized toArray(generator) returns an array of a specific type.

Be careful with parallel streams and the result may not be predictable.

Happy Learning !!

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.