Collectors utility class¶
The Collectors utility class is a public final class located in the java.util.stream package, primarily used in conjunction with the Stream.collect() method^[java8-collect.md]. It serves as an implementation of the Collector interface, which defines a mutable reduction operation^[java8-collect.md].
Functional Characteristics¶
Unlike reduce operations which are immutable, Collectors utilizes a mutable reduction strategy^[java8-collect.md]. This process relies on several key functional components defined in the Collector interface:
- Supplier: Creates a new result container^[java8-collect.md].
- Accumulator: Incorporates a new data element into the result container^[java8-collect.md].
- Combiner: Combines two result containers into one^[java8-collect.md].
- Finisher: Performs an optional final transform on the container to convert its type^[java8-collect.md].
Common Methods¶
Grouping¶
The groupingBy method allows for the classification of stream elements based on a function^[java8-collect.md]. It supports multiple signatures, including a downstream collector for further processing^[java8-collect.md].
- Example:
collect(Collectors.groupingBy(Student::getName))^[java8-collect.md] - With Downstream:
collect(Collectors.groupingBy(Student::getName, Collectors.counting()))^[java8-collect.md]
Concurrent grouping is also available via groupingByConcurrent(Function)^[java8-collect.md].
Partitioning¶
The partitioningBy method divides the stream elements based on a Predicate^[java8-collect.md].
- Example:
collect(Collectors.partitioningBy(student -> student.getScore() >= 90))^[java8-collect.md] - With Downstream:
collect(Collectors.partitioningBy(student -> student.getScore() >= 90, Collectors.counting()))^[java8-collect.md]
Related Concepts¶
- [[Streams API]]
- [[Java 8 Features]]
- [[Reduction operations]]
Sources¶
^[java8-collect.md]