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 a various helpful reduction operations like accumulating the elements in collection and summarizing the data based on criteria.

Convert Simple Stream of Strings to List :

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 :

Mumbai
Banglore
Delhi
Vijayawada

Convert Simple Stream of Objects to List :

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

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.


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 :

Mumbai
Banglore
Delhi
Vijayawada

Happy Learning 🙂