Java: Convert Stream to Array - Stack Abuse

Java: Convert Stream to Array

Introduction

In this tutorial, we'll be converting a Java Stream into a Java Array for primitive types, as well as objects.

Stream.toArray()

The toArray() method is a built-in method from the Stream class which is really convenient to use when converting from a Stream to an array. It works for both primitive types and objects, though, there's a slight difference in the usage.

The method returns a new array, which means that we'll be packing the results into a new array for storage. For objects, we'll have to specify the object type and provide an array constructor of that type to the method as well.

Primitive Types

Java 8 has special streams for primitive types, i.e., IntStream, LongStream and DoubleStream. Let's use an IntStream to store a range of integers, and then convert it into an array:

IntStream stream = IntStream.range(10, 20);
int[] array = stream.toArray();
System.out.println("Printing array ...");

for (int i = 0; i < array.length; ++i)
    System.out.print(array[i] + " ");

This results in:

Printing array ...
10 11 12 13 14 15 16 17 18 19 

Streams are handy for data manipulation, so you might want to do preprocessing on a stream, rather than an array, and convert it into one in the end:

IntStream stream = IntStream.range(10, 20);
// Filter out all even numbers
int[] array = stream.filter(x -> x%2 == 0).toArray();
System.out.println("\nPrinting even numbers ...");
for (int i = 0; i < array.length; ++i)
    System.out.print(array[i] + " ");

This results in:

Printing even numbers ...
10 12 14 16 18

Objects

For objects, the toArray() method takes in an array constructor reference for the respective object, and returns an array of that type. Let's make a Stream of String objects and convert it into an array:

// Create a List of Strings
List<String> list = new ArrayList<>();
list.add("John");
list.add("Jenny");
list.add("Martha");

// Stream the List
Stream<String> stream = list.stream();

// Create an array using the toArray() method
String[] array = stream.toArray(String[]::new);
System.out.println("Printing String array ...");
for (int i = 0; i < array.length; ++i)
    System.out.println(array[i]);

This results in:

Printing String array...
John
Jenny
Martha

Note: The toArray() method requires the array constructor to be used and we've used a method reference to specify the type - String[]::new. toArray() returns an array of the specified type, and if the type isn't specified, a mismatch will occur:

String[] array = stream.toArray();

The result is a compiler error:

Git Essentials

Check out this hands-on, practical guide to learning Git, with best-practices and industry-accepted standards. Stop Googling Git commands and actually learn it!

error: incompatible types: Object[] cannot be converted to String[]

Instead of the shorthand method references, we can also use Lambda Expressions to achieve this. Let's filter out only names that start with 'J':

// Create a List of Strings
List<String> list = new ArrayList<>();
list.add("John");
list.add("Jenny");
list.add("Martha");

// Stream the List
Stream<String> stream = list.stream();

// Filter the stream element and convert to array
String[] array = stream
        .filter(string -> string.startsWith("J"))
        .toArray(size -> new String[size]);
System.out.println("Printing names starting with 'J'...");
for (int i = 0; i < array.length; ++i)
    System.out.println(array[i]);

This produces:

Printing names starting with 'J'...
John
Jenny

Conclusion

In this article, we've converted a Stream into an array. This can be done for primitive and object arrays via the Stream.toArray() method, albeit, with slightly different usage.

Last Updated: September 9th, 2020

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Mehreen SaeedAuthor

I am an educator and I love mathematics and data science!

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    © 2013-2021 Stack Abuse. All rights reserved.