JAVA8-Collector interface源码分析

admin
2022-09-19 / 0 评论 / 127 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年09月19日,已超过676天没有更新,若内容或图片失效,请留言反馈。

Collector interface源码分析

源码

public interface Collector<T, A, R> {
        Supplier<A> supplier();
        BiConsumer<A, T> accumulator();
        Function<A, R> finisher();
        BinaryOperator<A> combiner();
        Set<Characteristics> characteristics();
}

说明:
1.T is the generic type of the items in the stream to be collected.
2.A is the type of the accumulator, the object on which the partial result will be accumulated during the
collection process.
3.R is the type of the object (typically, but not always, the collection) resulting from the collect
operation.

T:传入参数类型,A:需要进行处理的方法,R:处理后返回的结果

特征值:
CONCURRENT:并行的
UNORDERED:无序的
IDENTITY_FINISH:传入什么,返回什么

范例

toList()源码

1、入口

menu.stream().filter(t->t.isVegetarian()).collect(Collectors.toList())

2、Collectors.toList()源码:

    public static <T>
    Collector<T, ?, List<T>> toList() {
        return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
                                   (left, right) -> { left.addAll(right); return left; },
                                   CH_ID);
    }

3、最后也就是Collector接口

        CollectorImpl(Supplier<A> supplier,
                      BiConsumer<A, T> accumulator,
                      BinaryOperator<A> combiner,
                      Set<Characteristics> characteristics) {
            this(supplier, accumulator, combiner, castingIdentity(), characteristics);
        }

流程图

1、Collector执行流程图
Collector

执行过程:

  1. 通过Supplier supplier创建一个Container容器。
  2. 查看stream里面是否还有元素。
  3. 如果有,通过带2个入参一个返回结果参数的BiConsumer<A, T> accumulator进行数据处理。
  4. 处理完后通过finisher返回执行结果。

collect源码:
collect
说明:
1、获取容器
container = collector.supplier().get();
2、通过accumulator进行处理
forEach(u -> accumulator.accept(container, u));
3、执行完,返回执行结果
return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)

2、combiner并行执行执行流程图
combiner

产生多个supplier并行处理,然后将多个处理结果combiner成一个,然后将结果返回。

1

评论 (0)

取消