How do I use Collectors.toList() method?

The Collectors.toList() method is a convenient method in the java.util.stream.Collectors class that provides a Collector to accumulate input elements into a new List.

Here is a simple example of how to use Collectors.toList():

package org.kodejava.stream;

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

public class CollectorsToList {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        List<Integer> evenNumbers = numbers.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList());

        System.out.println(evenNumbers);
    }
}

Output:

[2, 4, 6, 8]

In this example, we create a stream of numbers and filter it to only include the even numbers. Then we collect the output into a List using Collectors.toList(). The result is a List<Integer> that only includes the even numbers.

Remember that collect is a terminal operation (meaning it triggers the processing of the data) and it returns a collection or other desired result type. In case of Collectors.toList(), the result is a List.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.