In Java, the java.util.stream.Collectors class is part of the Stream API introduced in Java 8. It provides a wide range of built-in reduction operations that can be used to collect elements from a stream into various data structures, apply transformations, and perform aggregations. These operations are essential for working with streams in a more structured and functional way. Here are some of the common methods and use cases for the Collectors class:
List names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());
Set uniqueNumbers = numbers.stream()
.collect(Collectors.toSet());
LinkedList linkedList =
stream.collect(Collectors.toCollection(LinkedList::new));
Map idToName = people.stream()
.collect(Collectors.toMap
(Person::getId, Person::getName));
String joinedNames = people.stream()
.map(Person::getName)
.collect(Collectors.joining(", "));
int totalAge = people.stream()
.collect(Collectors.summingInt(Person::getAge));
double averageAge = people.stream()
.collect(Collectors.averagingInt(Person::getAge));
long numberOfPeople = people.stream()
.collect(Collectors.counting());
Optional oldestPerson = people.stream()
.collect(Collectors.maxBy
(Comparator.comparing(Person::getAge)));
Map> partitioned = people.stream()
.collect(Collectors.partitioningBy
(p -> p.getAge() >= 18));
Map> partitioned = people.stream()
.collect(Collectors.partitioningBy
(p -> p.getAge() >= 18));
List upperCaseNames = people.stream()
.collect(Collectors.mapping
(Person::getName, Collectors.toList()));
These are just some of the common use cases for the Collectors class. You can combine and customize these operations to suit your specific needs when working with streams in Java. The Collectors class is a powerful tool for stream processing, simplifying the process of collecting and processing data in a functional and declarative style.