Top Description Inners Methods
java.util.stream

public Interface Collector<T, A, R>

Known Direct Implementers
java.util.stream.Collectors.CollectorImpl
Type Parameters
<T>
the type of input elements to the reduction operation
<A>
the mutable accumulation type of the reduction operation (often hidden as an implementation detail)
<R>
the result type of the reduction operation
Imports
java.util.Collections, .EnumSet, .Objects, .Set, java.util.function.BiConsumer, .BinaryOperator, .Function, .Supplier

A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.

Examples of mutable reduction operations include: accumulating elements into a Collection; concatenating strings using a StringBuilder; computing summary information about elements such as sum, min, max, or average; computing "pivot table" summaries such as "maximum valued transaction by seller", etc. The class Collectors provides implementations of many common mutable reductions.

A Collector is specified by four functions that work together to accumulate entries into a mutable result container, and optionally perform a final transform on the result. They are:

Collectors also have a set of characteristics, such as Characteristics#CONCURRENT, that provide hints that can be used by a reduction implementation to provide better performance.

A sequential implementation of a reduction using a collector would create a single result container using the supplier function, and invoke the accumulator function once for each input element. A parallel implementation would partition the input, create a result container for each partition, accumulate the contents of each partition into a subresult for that partition, and then use the combiner function to merge the subresults into a combined result.

To ensure that sequential and parallel executions produce equivalent results, the collector functions must satisfy an identity and an associativity constraints.

The identity constraint says that for any partially accumulated result, combining it with an empty result container must produce an equivalent result. That is, for a partially accumulated result a that is the result of any series of accumulator and combiner invocations, a must be equivalent to combiner.apply(a, supplier.get()).

The associativity constraint says that splitting the computation must produce an equivalent result. That is, for any input elements t1 and t2, the results r1 and r2 in the computation below must be equivalent:

A a1 = supplier.get();
    accumulator.accept(a1, t1);
    accumulator.accept(a1, t2);
    R r1 = finisher.apply(a1);  // result without splitting

    A a2 = supplier.get();
    accumulator.accept(a2, t1);
    A a3 = supplier.get();
    accumulator.accept(a3, t2);
    R r2 = finisher.apply(combiner.apply(a2, a3));  // result with splitting
 

For collectors that do not have the UNORDERED characteristic, two accumulated results a1 and a2 are equivalent if finisher.apply(a1).equals(finisher.apply(a2)). For unordered collectors, equivalence is relaxed to allow for non-equality related to differences in order. (For example, an unordered collector that accumulated elements to a List would consider two lists equivalent if they contained the same elements, ignoring order.)

Libraries that implement reduction based on Collector, such as Stream#collect(Collector), must adhere to the following constraints:

In addition to the predefined implementations in Collectors, the static factory methods of(Supplier, BiConsumer, BinaryOperator, Characteristics...) can be used to construct collectors. For example, you could create a collector that accumulates widgets into a TreeSet with:

Collector<Widget, ?, TreeSet<Widget>> intoSet =
        Collector.of(TreeSet::new, TreeSet::add,
                     (left, right) -> { left.addAll(right); return left; });
(This behavior is also implemented by the predefined collector Collectors#toCollection(Supplier)).

API Note

Performing a reduction operation with a Collector should produce a result equivalent to:

A container = collector.supplier().get();
    for (T t : data)
        collector.accumulator().accept(container, t);
    return collector.finisher().apply(container);

However, the library is free to partition the input, perform the reduction on the partitions, and then use the combiner function to combine the partial results to achieve a parallel reduction. (Depending on the specific reduction operation, this may perform better or worse, depending on the relative cost of the accumulator and combiner functions.)

Collectors are designed to be composed; many of the methods in Collectors are functions that take a collector and produce a new collector. For example, given the following collector that computes the sum of the salaries of a stream of employees:

Collector<Employee, ?, Integer> summingSalaries
        = Collectors.summingInt(Employee::getSalary))
If we wanted to create a collector to tabulate the sum of salaries by department, we could reuse the "sum of salaries" logic using Collectors#groupingBy(Function, Collector):
Collector<Employee, ?, Map<Department, Integer>> summingSalariesByDept
        = Collectors.groupingBy(Employee::getDepartment, summingSalaries);
Since
1.8
See Also
Stream#collect(Collector), Collectors

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static enum
Collector.Characteristics

Characteristics indicating properties of a Collector, which can be used to optimize reduction implementations.

Method Summary

Modifier and TypeMethod and Description
public BiConsumer<A, T>

Returns:

a function which folds a value into a mutable result container
accumulator
()

A function that folds a value into a mutable result container.

public Set<Collector.Characteristics>

Returns:

an immutable set of collector characteristics
characteristics
()

Returns a Set of Collector.Characteristics indicating the characteristics of this Collector.

public BinaryOperator<A>

Returns:

a function which combines two partial results into a combined result
combiner
()

A function that accepts two partial results and merges them.

public Function<A, R>

Returns:

a function which transforms the intermediate result to the final result
finisher
()

Perform the final transformation from the intermediate accumulation type A to the final result type R.

public static <
The type of input elements for the new collector
T
,
The type of intermediate accumulation result, and final result, for the new collector
R
>
Collector<T, R, R>

Returns:

the new Collector
of
(Supplier<R>
The supplier function for the new collector
supplier
,
BiConsumer<R, T>
The accumulator function for the new collector
accumulator
,
BinaryOperator<R>
The combiner function for the new collector
combiner
,
Collector.Characteristics...
The collector characteristics for the new collector
characteristics
)

Returns a new Collector described by the given supplier, accumulator, and combiner functions.

public static <
The type of input elements for the new collector
T
,
The intermediate accumulation type of the new collector
A
,
The final result type of the new collector
R
>
Collector<T, A, R>

Returns:

the new Collector
of
(Supplier<A>
The supplier function for the new collector
supplier
,
BiConsumer<A, T>
The accumulator function for the new collector
accumulator
,
BinaryOperator<A>
The combiner function for the new collector
combiner
,
Function<A, R>
The finisher function for the new collector
finisher
,
Collector.Characteristics...
The collector characteristics for the new collector
characteristics
)

Returns a new Collector described by the given supplier, accumulator, combiner, and finisher functions.

public Supplier<A>

Returns:

a function which returns a new, mutable result container
supplier
()

A function that creates and returns a new mutable result container.

Method Detail

accumulatorback to summary
public BiConsumer<A, T> accumulator()

A function that folds a value into a mutable result container.

Returns:BiConsumer<A, T>

a function which folds a value into a mutable result container

characteristicsback to summary
public Set<Collector.Characteristics> characteristics()

Returns a Set of Collector.Characteristics indicating the characteristics of this Collector. This set should be immutable.

Returns:Set<Collector.Characteristics>

an immutable set of collector characteristics

combinerback to summary
public BinaryOperator<A> combiner()

A function that accepts two partial results and merges them. The combiner function may fold state from one argument into the other and return that, or may return a new result container.

Returns:BinaryOperator<A>

a function which combines two partial results into a combined result

finisherback to summary
public Function<A, R> finisher()

Perform the final transformation from the intermediate accumulation type A to the final result type R.

If the characteristic IDENTITY_FINISH is set, this function may be presumed to be an identity transform with an unchecked cast from A to R.

Returns:Function<A, R>

a function which transforms the intermediate result to the final result

ofback to summary
public static <T, R> Collector<T, R, R> of(Supplier<R> supplier, BiConsumer<R, T> accumulator, BinaryOperator<R> combiner, Collector.Characteristics... characteristics)

Returns a new Collector described by the given supplier, accumulator, and combiner functions. The resulting Collector has the Collector.Characteristics.IDENTITY_FINISH characteristic.

Parameters
<T>
The type of input elements for the new collector
<R>
The type of intermediate accumulation result, and final result, for the new collector
supplier:Supplier<R>

The supplier function for the new collector

accumulator:BiConsumer<R, T>

The accumulator function for the new collector

combiner:BinaryOperator<R>

The combiner function for the new collector

characteristics:Collector.Characteristics[]

The collector characteristics for the new collector

Returns:Collector<T, R, R>

the new Collector

Exceptions
NullPointerException:
if any argument is null
ofback to summary
public static <T, A, R> Collector<T, A, R> of(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner, Function<A, R> finisher, Collector.Characteristics... characteristics)

Returns a new Collector described by the given supplier, accumulator, combiner, and finisher functions.

Parameters
<T>
The type of input elements for the new collector
<A>
The intermediate accumulation type of the new collector
<R>
The final result type of the new collector
supplier:Supplier<A>

The supplier function for the new collector

accumulator:BiConsumer<A, T>

The accumulator function for the new collector

combiner:BinaryOperator<A>

The combiner function for the new collector

finisher:Function<A, R>

The finisher function for the new collector

characteristics:Collector.Characteristics[]

The collector characteristics for the new collector

Returns:Collector<T, A, R>

the new Collector

Exceptions
NullPointerException:
if any argument is null
supplierback to summary
public Supplier<A> supplier()

A function that creates and returns a new mutable result container.

Returns:Supplier<A>

a function which returns a new, mutable result container

java.util.stream back to summary

public final Enum Collector.Characteristics

extends Enum<Collector.Characteristics>
Class Inheritance

Characteristics indicating properties of a Collector, which can be used to optimize reduction implementations.

Field Summary

Modifier and TypeField and Description
public static final Collector.Characteristics
CONCURRENT

Indicates that this collector is concurrent, meaning that the result container can support the accumulator function being called concurrently with the same result container from multiple threads.

public static final Collector.Characteristics
IDENTITY_FINISH

Indicates that the finisher function is the identity function and can be elided.

public static final Collector.Characteristics
UNORDERED

Indicates that the collection operation does not commit to preserving the encounter order of input elements.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static Collector.Characteristics
public static Collector.Characteristics[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

CONCURRENTback to summary
public static final Collector.Characteristics CONCURRENT

Indicates that this collector is concurrent, meaning that the result container can support the accumulator function being called concurrently with the same result container from multiple threads.

If a CONCURRENT collector is not also UNORDERED, then it should only be evaluated concurrently if applied to an unordered data source.

IDENTITY_FINISHback to summary
public static final Collector.Characteristics IDENTITY_FINISH

Indicates that the finisher function is the identity function and can be elided. If set, it must be the case that an unchecked cast from A to R will succeed.

UNORDEREDback to summary
public static final Collector.Characteristics UNORDERED

Indicates that the collection operation does not commit to preserving the encounter order of input elements. (This might be true if the result container has no intrinsic order, such as a Set.)

Constructor Detail

Characteristicsback to summary
private Characteristics()

Method Detail

valueOfback to summary
public static Collector.Characteristics valueOf(String name)
valuesback to summary
public static Collector.Characteristics[] values()