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

  1. 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
    
  2. Grouping:
    • Collectors provides grouping operations, such as groupingBy(), 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));
    
  3. 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));
    
  4. Counting:
    • Collectors.counting() is used to count the number of elements in a stream.
    long count = words.stream()
                      .collect(Collectors.counting());  // Counts total elements
    
  5. 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
    
  6. 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 a List.
  • toSet(): Collects the stream into a Set.
  • toMap(): Collects the stream into a Map.
  • 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.