Skip to content

Java 8 Stream Collector

In Java 8, the Stream.collect() operation is a terminal operation used to transform the elements of a stream into a different form, such as a Collection, Map, or summary result.^[600-developer__java__java8__java8-collect.md]

Core Architecture

The collection mechanism relies on the java.util.stream.Collector interface and the utility class java.util.stream.Collectors.^[600-developer__java__java8__java8-collect.md]

A Collector is defined by four specific functions that describe how to accumulate elements into a mutable result container:^[600-developer__java__java8__java8-collect.md] * Supplier: Creates a new result container. * Accumulator: Incorporates a new data element into the result container. * Combiner: Combines two result containers into one. * Finisher: Performs an optional final transform on the container (e.g., converting a mutable container to an immutable result).

This approach contrasts with reduce operations, which typically process elements into an immutable result.^[600-developer__java__java8__java8-collect.md]

Common Operations

Grouping

The groupingBy collector is used to classify input elements based on a function.^[600-developer__java__java8__java8-collect.md]

  • Simple Grouping: Elements are grouped by a specific classification function.
    collect(Collectors.groupingBy(Student::getName))
    
  • Grouping with Downstream Collector: A secondary collector can be applied to the grouped elements.
    collect(Collectors.groupingBy(Student::getName, Collectors.counting()))
    
  • Concurrent Grouping: For parallel streams, groupingByConcurrent can be used.^[600-developer__java__java8__java8-collect.md]

Partitioning

The partitioningBy collector divides the input elements into two groups based on a Predicate (true/false).^[600-developer__java__java8__java8-collect.md]

  • Simple Partitioning:
    collect(Collectors.partitioningBy(student -> student.getScore() >= 90));
    
  • Partitioning with Downstream Collector: Applies a specific collector to the partitioned values.
    collect(Collectors.partitioningBy(student -> student.getScore() >= 90, Collectors.counting()));
    
  • [[Java Streams]]
  • [[Functional Programming]]
  • [[MapReduce]]

Sources

  • 600-developer__java__java8__java8-collect.md