Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

How to convert Java 8 Stream to Array and ArrayList in Java? Example Tutorial

It's relatively easy to convert a Stream to an array in Java 8 by using the toArray() method of java.util.Stream class. By using this method you can convert any type of Stream to a corresponding array like a Stream of Strings can be converted into an array of String, or a Stream of integers can be converted into an array of Integers. The Stream.toArray() method is also overloaded, the one which doesn't take any parameter returns an Object[] which might not be very useful, particularly if you want to convert Stream of T to an array of T.

On the other hand, the overloaded version of the toArray(IntFunction[] generator) returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.

This toArray() method accepts a function that produces a new array of the desired type. The generator function takes an integer, which is the size of the desired array, and produces an array of the desired size.

If you are familiar with method reference then this can be expressed even more concisely with an array constructor reference. You can pass this method a lambda expression or use the array reference to further shorten it as shown by a couple of examples in this article.

Btw, let me tell you that we'll cover converting Stream to both array and ArrayList, the dynamic array of JDK library.

Even though you can still use all the tricks I have shown before to convert an array to ArrayList, there are added benefits of using new methods provides by Java 8 as they minimize additional intermediate steps.

2 Ways to convert Stream to Array in Java 8

Now, let's see a couple of ways to convert a Java 8 Stream into an array in Java, using this way you can convert a Stream of Integer into Integer array and so on. You can even transform object using map() and flatMap() function before you convert them into an array.   

Btw, if you are wondering how Stream works in Java and how to use Stream to transform object and collect object into array or list, here is a nice diagram which explains a common Stream pipeline

How Stream API works in Java

1. Stream to Array using a lambda expression in Java 8

Here is the simplest way to convert a Stream of objects into an array of Objects. Suppose, the library object is a list of books and we need to convert that into an array.

Of course, you can directly convert a list to an array without going via Stream as shown here, but for the purpose of this example, we'll use Stream to perform that conversion.

Another reason to use Stream is filtering and lazy evaluation, for example, if you just want fiction books from a list of books, if you directly convert a list to an array, then you won't be able to filter it, but by using Stream you can just use the filter() method for lazy filtering.

Once you got the stream with the interesting value, just call the toArray() method and passing them a generator function which will be used to convert each element of Stream to the corresponding object as shown in the following example:

Book[] books =
                      .filter(b -> p.getTopic() == FICTION)
                      .toArray(size -> new Integer[size]);  

Now, the book's array contains all books from the list library where the topic is FICTION. You can see that we pass the generator function using a lambda expression.

If you want to learn more about new features introduced in Java 8 like lambdas, Stream, and other enhancements then I also suggest you take a look at the Functional Programming in Java course on Udemy. It's again a nice little course that provides an overview of all important Java 8 features like Stream and Lambdas.

How to convert Java 8 Stream to Array or ArrayList - Example Tutorial

2. Stream to an Array using a Method Reference

Now, you can make the above example, even more, shorter by using the method reference in form of a constructor reference. This will eliminate the lambda expression we have passed in the above example:

Book[] books =
                      .filter(b -> p.getTopic() == FICTION)

You can see that this example is even more elegant, classic, and easy to understand than the previous example.

If you are not very familiar with method reference and constructor reference then I suggest you join a good course on  Java 8 which is focused on stream and lambda expression like From Collections to Streams in Java 8 Using Lambda Expressions on Pluralsight by Jose Paurmand, a Java Champion.

Stream to an Array using a Method Reference

3. Stream to ArrayList in Java 8

Now, you have seen how to convert a Java 8 Stream to the array, you can use all the techniques you already know to convert an array to ArrayList to get an ArrayList, but what is the fun if you still have to do it in the old Java way? So, let's find out the new way to convert Java 8 Stream to ArrayList.

If you recall our previous examples e.g. converting a Stream to List and converting Stream to Map, then you know that you can use the collect() method to accumulate stream elements in the choice of your collection.

You can use the utility class Collectors and its conversion methods like toList() and toMap() to get the List and Map from a Stream in Java 8.

This is fine, but in order to get ArrayList from Stream, you just need to know a little bit more. You need to know that the Collectors.toList() method can return any type of list, as it doesn't provide any guarantee on the type, thread-safety, or immutability of the returned List.

Though, there is a similar method called toCollection() which accepts a supplier, which can be used to convert Stream to ArrayList.

All you need to do is provide the ArrayList::new as supplier and toCollection() method will wrap all elements of a stream in an ArrayList and return its reference to you.  You can read Java SE 8 for the Really Impatient bookto learn more about this behavior of Collector.

Now, let's see a real-life example of how to convert Java 8 Stream to ArrayList in Java.

ArrayList<Book> listOfBooks =
                                     .filter(b -> p.getTopic() == BIOGRAPHY

You can see that by using the Collectors or toCollection() method it's extremely easy to convert a Stream of values into an ArrayList of objects.

Here is also a Java program to demonstrate various ways to convert a Stream to Array and ArrayList in Java 8:

How to convert Java 8 Stream to Array or ArrayList

That's all about how to convert a Java 8 Stream to Array and ArrayList in Java. It's not that difficult, you just need to know the right methods from Stream API to do the conversion.

Use the Stream.toArray(IntFunction) method when you want a typed array from Streams like an Integer array from a stream of Integer objects or a String array from a stream of Strings. Alternatively you can use toArray() method to get an Object[].

Similarly, In order to convert Stream to ArrayList, you can use toCollection() method by passing the ArrayList constructor reference. Don't use the toList() method because it doesn't specify which type of List it will return.

You can further see the following resources to learn more about Stream and interoperability with the Java Collection framework.

Related Java 8 Tutorials and Examples you may like
  • 5 Free Courses to learn Java 8 and 9 (courses)
  • 5 Books to Learn Java 8 Better? (read here)
  • 7 Best Courses to learn Data Structure and Algorithms (best courses)
  • 5 Best Courses to learn Java Collections and Streams (best courses)
  • 10 Examples of converting a List to Map in Java 8 (see here)
  • 5 lambda expression and Stream courses for beginners (online courses)
  • Java 8 Comparator Example (check here)
  • 10 Data Structure Courses for Coding interviews (online courses)
  • Collection of best Java 8 tutorials (click here)
  • Free Courses to learn Spring Framework (free courses)
  • How to use debug Stream in Java 8 (tutorial)
  • Free Courses to learn Spring Boot in-depth (free courses)
  • Difference between abstract class and interface in Java 8? (answer)
  • Difference between and Stream.flatMap() in Java 8? (answer)
  • How to sort the may by values in Java 8? (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • Top 5 Course to master Java 8 Programming (courses)

Thanks for reading this article so far. If you like this Java 8 Stream to Array conversion tutorial and example then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S.: If you just want to learn more about new features in Java 8 then please see these Java 9 to Java 13 courses from Pluralsight.  It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API, and other miscellaneous changes.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.