How to Convert a Stream to Set and List Collection in Java 8 - Example

Hello guys, if you are following Java releases then you know that introduction of Stream class is one f the most important addition in Java 8 as it makes processing bulk data really easy. Since data is the core part of any application and probably is the most important thing now than ever, a good knowledge of how to use Stream class effectively is important like how to work between Collections and Stream classes. If you have worked with Stream then you would have noticed that even though we can easily create a stream from a List and Set by using the stream() method added on java.uti.Collection interface, unfortunately, Stream class doesn't have a method to convert a Stream back to List or Set or any other data structure in Java.

For example, many times we want to make a big list, filter some elements, and get them into another list. if you try to do stream.filter().toList() it will not work because there is not toList() or toSet() method on Stream.

So how do you convert or collect data from a Stream into a Collection class like List or Set? Well by using Collectors utility class, which like collections provides several utility methods to collect elements of the stream into different collections like ArrayList, LinkedList, HashSet, etc.

Collectors class is very similar to the Collections class which also contains a lot of static utility methods to operate on collections.

Btw, If you are new to Java 8 then I also suggest you take a good course to learn new features introduced in Java 8, particularly lambdas and Stream API. If you ask me then I would suggest The Complete Java MasterClass on Udemy and What's New in Java 8 course on Pluralsight, former is a complete course to learn Java, including Java 8 and other recent Java features, while later is a short course focused on Java 8 features like lambda expression and Stream.





Java Program to convert Stream to List and Set in Java

In the past, I have shared 10 examples of Collectors in Java 8 to show you the full power of what Collectors can do and why it is one of the most important classes of Java 8 Stream API, and today, I'll show you a simple example of using Collectors and Stream.collect() method to convert Stream to List and Set in Java 8.



Without wasting any more of your time, here is a simple example of how you do it. It also easier to print elements from Streams using the forEach() method.

package test;
 
import java.util.Arrays; 
import java.util.List; 
import java.util.Set; 
import java.util.stream.Collectors; 
 
/**
 
 * Java Program to demonstrate how to convert Stream to List in Java. 
 * Stream API also provides a Collectors class to convert the stream to
 * any collection type like List, Set, ArrayList, HashSet etc. 
 * 
 * @author Javin
  */
 
public class StreamToListAndSetExample{ 
 
    public static void main(String args[]) {
  
        // we have a list of even numbers 
        List even = Arrays.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20);
 
        System.out.println("list of even numbers : " + even);
 
  
        // now we need list of even numbers which are are greater than 10 
        // but we sadly only know how to filter string and print, but 
        // how to get the result in a separate list?
 
        even.stream()
            .filter(i -> (i > 10) )
            .forEach(System.out::println);
 
        // fortunately stream has a collect() method, which allows you to collect 
        // stream element into any collection. 
        // use Collectors toList() method to convert stream to list in Java 8
 
        List evenLessThan10 = even.stream()
                                  .filter(i -> (i       
        System.out.println("list of even numbers less than 10 : " 
                                  + evenLessThan10);
 
        // we can even convert Stream to Set by using this method
        Set setOfIntegers = even.stream()
                                .map(a -> (a*a))
                                .collect(Collectors.toSet());
 
        System.out.println("set of square of even numbers : " 
                                     + setOfIntegers);
    }
 
 
}
 
Output :
run:
list of even numbers : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
12
14
16
18
20
list of even numbers less than 10 : [2, 4, 6, 8]
set of square of even numbers : [16, 64, 144, 256, 400, 4, 36, 100, 196, 324]


That's all about how to convert Stream to List and Set in Java. Since Stream is just a temporary holder for processing data, you will eventually find collecting data from Stream into a List or Set. The key method and class to remember here is the collect() method of Stream class and Collectors class which offers several useful methods to convert Stream to List, Set, and other Collections classes.

Further Learning
The Complete Java MasterClass
What's New in Java 8
Java SE 8 for Programmers (book)
Refactoring to Java 8 Streams and Lambdas Self- Study Workshop


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:
  • The 2020 Java Developer RoadMap (see)
  • 10 Courses to learn Java in-depth (courses)
  • How to use filter() method in Java 8 (tutorial)
  • Top 5 Courses to learn Functional Programming in Java (courses)
  • 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 Stream class in Java 8 (tutorial)
  • Top 5 Courses to learn Lambdas and Stream in-depth (courses)
  • 5 Books to Learn Java 8 from Scratch (books)
  • Top 5 Courses to become a full-stack Java developer (courses)
  • What is the default method in Java 8? (example)
  • 10 Java and Spring Boot Courses you can buy on Udemy sale (courses)
  • How to join String in Java 8 (example)
  • Difference between abstract class and interface in Java 8? (answer)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to sort the map by keys in Java 8? (example)
  • How to convert List to Map in Java 8 (solution)
  • 10 examples of Optionals in Java 8? (example)

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

P. S. - If you are looking for free courses to learn all the new and important Java features introduced between Java 8 and Java 13 then you can also see this list of online Java courses on Medium. It includes short and focused courses to learn new JDK features from JDK 8 to JDK 13.

No comments:

Post a Comment

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