Java 8 Stream collect to list example

The Collectors.toList returns a collector that accumulates the input elements into a new list.

Java 8 Stream collect to list example

The example filters a list of strings and transforms the stream into a list. We filter the list to include only strings whose length is equal to four.


import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class JavaCollectToListEx {

    public static void main(String[] args) {

        List < String > programmingLanguages = new ArrayList < > ();
        programmingLanguages.add("C");
        programmingLanguages.add("C++");
        programmingLanguages.add("Java");
        programmingLanguages.add("Kotlin");
        programmingLanguages.add("Python");
        programmingLanguages.add("Perl");
        programmingLanguages.add("Ruby");

        // filter all four character words into a list
        List < String > result = programmingLanguages.stream().filter(word -> word.length() == 4)
                .collect(Collectors.toList());

        System.out.println(result);
    }
}

Output:

[Java, Perl, Ruby]

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments