Collectors
class?Collectors
is a utility class that provides various implementations of reduction operations such as grouping elements, collecting elements to different collections, summarizing elements according to various criteria, etc. The different functions in the Collectors
class are usually used as the final operations on streams.
toList()
?toList()
is a static method of the Collectors
class that is used to collect/accumulate all the elements to a new List
. The type, mutability, serializability, and thread safety of the List
returned are not guaranteed.
The toList
method is defined in the Collectors
class. The Collectors
class is defined in the java.util.stream
package. To import the Collectors
class, check the following import statement.
import java.util.stream.Collectors;
public static <T> Collector<T, ?, List<T>> toList()
The method has no parameters.
This method returns a collector that collects all the input elements in the encountered order.
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {public static void main(String[] args){List<String> stringList = Arrays.asList("educative", "io", "edpresso");System.out.println("Stream before modification - " + stringList);Stream<String> stringStream = stringList.stream();List<String> uppercaseList = stringStream.map(String::toUpperCase).collect(Collectors.toList());System.out.println("Resulting list after modification - " + uppercaseList);}}
stringList
.stringList
.stringList
.map
method and collect the resulting elements to a new list using the toList
method.