What is the purpose of the `Collectors` class in Streams?
The Collectors
class in Java provides a set of static utility methods to facilitate the reduction of elements in a stream into collections, such as lists, sets, or maps. It is part of the java.util.stream
package and is commonly used in combination with the Stream.collect()
method.
Key Purposes of Collectors
- Collection Operations:
- It helps in collecting the elements of a stream into different types of collections.
List<String> words = Arrays.asList("Java", "Python", "C++"); List<String> wordList = words.stream() .collect(Collectors.toList()); // Collects into a List
- Grouping:
Collectors
provides grouping operations, such asgroupingBy()
, which collects elements based on a classifier function.
List<String> words = Arrays.asList("Java", "JavaScript", "Python"); Map<Integer, List<String>> groupedByLength = words.stream() .collect(Collectors.groupingBy(String::length));
- Partitioning:
- It allows partitioning elements into two groups based on a predicate using
partitioningBy()
.
List<String> words = Arrays.asList("Java", "Python", "C++"); Map<Boolean, List<String>> partitioned = words.stream() .collect(Collectors.partitioningBy(word -> word.length() > 4));
- It allows partitioning elements into two groups based on a predicate using
- Counting:
Collectors.counting()
is used to count the number of elements in a stream.
long count = words.stream() .collect(Collectors.counting()); // Counts total elements
- Summing, Averages, and Other Reductions:
- It provides several methods like
summarizingInt()
,summarizingDouble()
,reducing()
, and others to perform aggregate operations like summing or averaging.
int sum = words.stream() .collect(Collectors.summingInt(String::length)); // Sums the lengths of words
- It provides several methods like
- Joining:
Collectors.joining()
allows concatenating elements into a single string with optional delimiters, prefixes, or suffixes.
String result = words.stream() .collect(Collectors.joining(", ", "[", "]")); // Output: [Java, Python, C++]
Key Methods in Collectors
toList()
: Collects the stream into aList
.toSet()
: Collects the stream into aSet
.toMap()
: Collects the stream into aMap
.joining()
: Concatenates the elements into a single string.groupingBy()
: Groups the elements based on a classifier function.partitioningBy()
: Partitions the stream into two groups based on a predicate.
In summary, the Collectors
class provides a rich set of predefined collection operations for reducing, grouping, partitioning, counting, and more, making it easier to process streams and gather results into desired data structures.