Wednesday , June 28 2017
Home / java8 / Java 8 How to convert Stream to List

Java 8 How to convert Stream to List

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);
    }
}

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()));
    }

}

Mumbai
Banglore
Delhi
Vijayawada

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Java 8 Read File Line By Line Example

In this tutorials, I am going to show you how to read a File line …

Leave a Reply

Your email address will not be published. Required fields are marked *