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
.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024