Convert Stream to List using Stream collect(toList())

Stream collect()

collect() is an eager method.

This method collects elements from a stream and stores them in a collection.

collect(toList()) collects elements from a stream to a List

 
convert stream to List

Convert stream to List – collect(toList())

 

Example 1: collect a List

Lets see an example of collect() to build a List out of a Stream.

List<Integer> collected = Stream.of(1,2,3,4,5)
        .collect(Collectors.toList());
collected.forEach(System.out::println);

Output:

1
2
3
4
5

We can also use a static import and write the code as :

import static java.util.stream.Collectors.toList;
...
...
List<Integer> collected = Stream.of(1,2,3,4,5)
        .collect(toList());

Lets see some more examples of collect(toList()).
 

Example 2: collect() with map()

In this example, map() method converts each name to uppercase and then collect() method collects the uppercase names in a list.

List<String> countries = Arrays.asList("Germany", "England", "China",
    "Denmark", "Brazil", "France", "Australia");
List<String> upCountries = countries.stream().map(name -> name.toUpperCase())
                    .collect(toList());
upCountries.forEach(System.out::println);

Running this program will print the country names in uppercase.

GERMANY
ENGLAND
CHINA
DENMARK
BRAZIL
FRANCE
AUSTRALIA
 

Example 3 : collect() with filter()

List<String> countries = Arrays.asList("Germany", "England", "China",
    "Denmark", "Brazil", "France", "Australia");
List<String> filteredList =
    countries.stream()
    .filter(item -> item.startsWith("A"))
    .collect(toList());
filteredList.forEach(System.out::println);

Output:

Australia

 

Similar to collect(toList()), we also have methods like collect(toSet()) and collect(toMap()).

Convert stream to a Set

Convert stream to a Map

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags