Java Collectors

Introduction

In Java, Collectors is a utility class in the java.util.stream package that provides various methods for collecting stream elements into different types of results, such as lists, sets, or maps. It is commonly used in conjunction with the Stream API to process and collect data efficiently.

Table of Contents

  1. What are Collectors?
  2. Commonly Used Methods
  3. Examples of Collectors
  4. Real-World Use Case
  5. Conclusion

1. What are Collectors?

Collectors is a final class that provides static methods for obtaining Collector instances. These instances implement various reduction operations, such as accumulating elements into collections, summarizing elements, and joining strings.

2. Commonly Used Methods

Here are some commonly used methods in the Collectors class:

  • toList(): Collects elements into a List.
  • toSet(): Collects elements into a Set.
  • toMap(): Collects elements into a Map.
  • joining(): Concatenates elements into a String.
  • counting(): Counts the number of elements.
  • summarizingInt(), summarizingDouble(), summarizingLong(): Collects statistics, such as count, sum, min, average, and max.
  • groupingBy(): Groups elements by a classifier function.
  • partitioningBy(): Partitions elements into two groups based on a predicate.

3. Examples of Collectors

Example 1: Collecting to a List

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectToListExample {
    public static void main(String[] args) {
        List<String> list = Stream.of("apple", "banana", "cherry")
                                  .collect(Collectors.toList());
        System.out.println("List: " + list);
    }
}

Output:

List: [apple, banana, cherry]

Example 2: Collecting to a Set

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectToSetExample {
    public static void main(String[] args) {
        Set<String> set = Stream.of("apple", "banana", "apple")
                                .collect(Collectors.toSet());
        System.out.println("Set: " + set);
    }
}

Output:

Set: [banana, apple]

Example 3: Collecting to a Map

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectToMapExample {
    public static void main(String[] args) {
        Map<String, Integer> map = Stream.of("apple", "banana", "cherry")
                                         .collect(Collectors.toMap(fruit -> fruit, String::length));
        System.out.println("Map: " + map);
    }
}

Output:

Map: {banana=6, cherry=6, apple=5}

Example 4: Joining Strings

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JoiningExample {
    public static void main(String[] args) {
        String result = Stream.of("apple", "banana", "cherry")
                              .collect(Collectors.joining(", "));
        System.out.println("Joined String: " + result);
    }
}

Output:

Joined String: apple, banana, cherry

Example 5: Counting Elements

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CountingExample {
    public static void main(String[] args) {
        long count = Stream.of("apple", "banana", "cherry")
                           .collect(Collectors.counting());
        System.out.println("Count: " + count);
    }
}

Output:

Count: 3

Example 6: Grouping By

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class GroupingByExample {
    public static void main(String[] args) {
        Map<Integer, List<String>> groupedByLength = Stream.of("apple", "banana", "cherry")
                                                           .collect(Collectors.groupingBy(String::length));
        System.out.println("Grouped by Length: " + groupedByLength);
    }
}

Output:

Grouped by Length: {5=[apple], 6=[banana, cherry]}

Example 7: Partitioning By

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class PartitioningByExample {
    public static void main(String[] args) {
        Map<Boolean, List<String>> partitioned = Stream.of("apple", "banana", "cherry")
                                                       .collect(Collectors.partitioningBy(s -> s.length() > 5));
        System.out.println("Partitioned: " + partitioned);
    }
}

Output:

Partitioned: {false=[apple], true=[banana, cherry]}

4. Real-World Use Case: Summarizing Integer Statistics

import java.util.IntSummaryStatistics;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SummarizingIntExample {
    public static void main(String[] args) {
        IntSummaryStatistics stats = IntStream.of(1, 2, 3, 4, 5)
                                              .collect(Collectors.summarizingInt(Integer::intValue));
        System.out.println("Summary Statistics: " + stats);
    }
}

Output:

Summary Statistics: IntSummaryStatistics{count=5, sum=15, min=1, average=3.000000, max=5}

Conclusion

The Collectors class is used in Java for collecting and processing data using the Stream API. Its various methods allow developers to accumulate elements into collections, summarize data, and perform other reduction operations efficiently. Using Collectors can greatly enhance code readability and maintainability, especially in data processing contexts.

Comments