java8 Collector(收集器)

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:将结果容器转换成最终的表示

下面是

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值