Collector
什么是Collector
JavaDoc中对Collector的描述如下:
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.
Collector是一种可变的汇聚操作,它将输入元素累积到一个可变的结果容器中。在所有的元素处理完成后,Collector将累积的结果转换成一个最终的表示(这是一个可选的操作)。Collector支持串行和并行两种方式执行。
Collector接口中声明五个方法和一个枚举常量:
public interface Collector<T, A, R> {
Supplier<A> supplier();
BiConsumer<A, T> accumulator();
BinaryOperator<A> combiner();
Function<A, R> finisher();
Set<Characteristics> characteristics();
enum Characteristics {
CONCURRENT,
UNORDERED,
IDENTITY_FINISH
}
....
}
Collector接口有三个泛型,它们的含义如下:
- T:输入的元素类型
- A:累积结果的容器类型
- R:最终生成的结果类型
Collector工作原理
Collector通过下面四个方法协同工作以完成汇聚操作:
- supplier: 创建新的结果容器
- accumulator:将输入元素合并到结果容器中
- combiner:合并两个结果容器(并行流使用,将多个线程产生的结果容器合并)
- finisher:将结果容器转换成最终的表示
下面是串