In this tutorials, we are going to learn how to convert stream to list in Java 8

Java 8 convert Stream to List :

Java 8 provides a Collectors class to convert Stream to List. Collectors class is a final class, which is an implementation of Collector interface.

The Collector class provides various helpful reduction operations like accumulating the elements in the collection and summarizing the data based on criteria.

Convert Simple Stream of Strings to List :

Java8_StreamToList.java

public class Java8_StreamToList {
    public static void main(String args[]) {
        Stream<String> cities = Stream.of("Mumbai", "Banglore", "Delhi",
                "Vijayawada");
        List<String> cityList = cities.collect(Collectors.toList());
        cityList.forEach(System.out::println);
    }
}

Output :

Terminal
Mumbai
Banglore
Delhi
Vijayawada

Convert Simple Stream of Objects to List :

We can also convert the Stream of user-defined objects into List. Here I am going to create a stream of City class and convert the same into List.

City.java

City.java

class City {
    private int cityId;
    private String cityName;

    public City(int cityId, String cityName) {
        super();
        this.cityId = cityId;
        this.cityName = cityName;
    }

    public int getCityId() {
        return cityId;
    }

    public String getCityName() {
        return cityName;
    }

}

Converting Stream (contains City Objects) to List.

Java8_StreamToList.java

public class Java8_StreamToList {
    public static void main(String args[]) {
        convertObjets();
    }

    public static void convertObjets() {
        Stream<City> cities = Stream.of(new City(1, "Mumbai"), new City(1,
                "Banglore"), new City(1, "Delhi"),new City(1, "Vijayawada"));
        List<City> cityList = cities.collect(Collectors.toList());
        cityList.forEach(city->System.out.println(city.getCityName()));
    }

}

Output :

Terminal
Mumbai
Banglore
Delhi
Vijayawada

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment