How to Convert Stream to ArrayList in Java 8 - Collectors.toCollection() Example, Tutorial

You can use Collectors.toList(), toSet() and toMap() to get all elements of Stream into any Collection e.g. List, Set or Map, but if you want to get a particular collection e.g. ArrayList, then you need to use Collectors.toCollection(ArrayList::new) method. This method first creates an ArrayList using method reference and then adds all elements of Stream into the ArrayList. It's very useful if you have a long list of String and you want to create a smaller list containing only String starting with the letter "b" e.g. "Bluehost". All you need to do is first get the stream from List by calling stream() method, then call the filter() method to create a new Stream of filtered values and finally call the Collectors.toCollection(ArrayList::new) to collect those elements into an ArrayList.

The java.util.stream.Collectors class also allows you to perform useful reduction operations like accumulating stream elements into collections like the list, set or map.

It provides convenient utility methods like toList() to get a list of elements from Stream, toSet() to get elements inside a Set from Stream and toMap() to create a Map from the object stored in Stream.

If you don't want to collect but just want to print, you can also use the forEach() method to print all elements of Stream in Java 8. You'll see a couple of examples to understand the concept better in this article.

But when you use toList() method there are no guarantees on the type, mutability, serializability, or thread-safety of the List returned, that's why if you need an ArrayList, you should use toCollection() method. 

You can also see The Complete Java MasterClass course on Udemy to learn more about effective use of Collectors in Java 8. It is also the most up-to-date course to learn Java and recently updated to cover the latest Java version, Java 11.




Java Program to get ArrayList from Stream in Java 8

Here is our sample Java program to demonstrate how to get the ArrayList from the Stream in Java. It shows how you can use the Collectors to collect the result in various collections.

Btw, you can use the static import feature of Java to make the code more readable, just statically import Collectors methods and instead of writing Collectors.collect() just write collect() or Collectors.toList() just write the toList().

This will make your code concise and more readable.

How to convert Stream to ArrayList in Java 8 - Collector example

Remember when you call toList(), toSet() or toMap() method it's not guaranteed which implementation will return. If you want a specific collection type then just ask for it like we have asked for ArrayList here.

Similarly, if you are converting Stream to Map, you can ask for LinkedHashMap if you want to preserve order. If you are interested to learn Stream API in depth, you can also check From Collections to Streams in Java 8 Using Lambda Expressions course on Pluralsight, one of the best course to learn Stream in depth.


Stream to ArrayList in Java 8
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/*
 * Java Program to show how to get the ArrayList
 * from Stream in Java 8. 
 */
public class Java8Demo {

    public static void main(String args[]) {

        List<Integer> numbers = Arrays.asList(100, 12001, 2001, 2003,
                                              120, 20, 3, 4);
        System.out.println("original list: " + numbers);

        // converting Stream to List in Java
        List<Integer> listOf100s = numbers.stream()
                .filter(num -> num > 100)
                .collect(Collectors.toList());
        System.out.println("list of numbers greater than 100: " + listOf100s);

        // Converting Stream to ArrayList in Java
        List<Integer> listOf200s = numbers.stream()
                .filter(num -> num > 200)
                .collect(Collectors.toCollection(ArrayList::new));
        System.out.println("list of numbers greater than 200: " + listOf200s);
        
    }

}

Output
original list: [100, 12001, 2001, 2003, 120, 20, 3, 4]
list of numbers greater than 100: [12001, 2001, 2003, 120]
list of numbers greater than 200: [12001, 2001, 2003]


That's all about How to get an ArrayList from Stream in Java 8 or how to convert Stream to ArrayList in Java. As you have seen, it's simple, all you need to do is use the Collectors class and its toCollection() method.

This method accepts a Supplier, a functional interface which returns a new, empty Collection of an appropriate type. You can also use the toList(), toSet(), and toMap() method from Collectors class to convert Stream to a List, Set, or Map in Java.

Just remember that ArrayList will preserve the order only if Stream is not parallel. For parallel Stream, ArrayList might have elements in different orders as they were added.

Further Reading
The Complete Java MasterClass
Java SE 8 for Really Impatient
From Collections to Streams in Java 8 Using Lambda Expressions


Related Java 8 Tutorials
If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:

  • 5 Free Courses to learn Java 8 and Java 9 (courses)
  • 5 Books to Learn Java 8 from Scratch (books)
  • 10 examples of Optional in Java 8? (example)
  • How to join String in Java 8 (example)
  • How to sort the may by values in Java 8? (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • How to use peek() method in Java 8 (example)
  • How to convert List to Map in Java 8 (solution)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to sort the map by keys in Java 8? (example)
  • How to use Stream class in Java 8 (tutorial)
  • How to use filter() method in Java 8 (tutorial)
  • Difference between abstract class and interface in Java 8? (answer)
  • Top 5 Online Courses to Master Java 8 Concepts (courses)

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or feedback then please drop a comment.

P.S.: If you just want to learn more about new features in Java 8 then please see the course What's New in Java 8. It explains all the important features of Java 8 e.g. lambda expressions, streams, functional interfaces, Optional, new Date Time API and other miscellaneous changes.

2 comments: