Stream collect 核心源碼解讀

使用示例代碼

        //一個string數組流對象
        Stream<String> streamList = Stream.of("aa","bb","cb","dg");
        /**
         * 第一個參數: 接受一個需要返回的類型的空對象 ,作爲最後返回的容器
         * 第二個參數: 獲取當前流中的元素,存入到容器【第一個對象】
         * 第三個參數: 猜測:1、因爲流支持鏈式編程  2、爲了支持並行流
         *  第三個參數,會將之前的流處理的返回結果集合並的當前容器【第一個參數】,
         * 最後返回包含所有數據的集合
         */
        List<String> list1 = streamList.collect(
            () -> new ArrayList(),
            (theList,item) -> theList.add(item),
            (theList,theList2) ->theList.addAll(theList2)
        );

接口中用到的函數式接口簡介

//沒有入參,返回一個需要的對象 
@FunctionalInterface
public interface Supplier<T> { T get(); }

//兩個入參,通過accept實現類處理 ,無出參
@FunctionalInterface
public interface BiConsumer<T, U> { void accept(T t, U u); }

源碼解析

Stream類中的接口

<R> R collect(Supplier<R> supplier,
             BiConsumer<R, ? super T> accumulator,
             BiConsumer<R, R> combiner);

實現類 : 主要調用了ReduceOps.makeRef

supplier :供應商
accumulator: 蓄電池
combiner : 組合器,合成儀

abstract class ReferencePipeline<P_IN, P_OUT>
        extends AbstractPipeline<P_IN, P_OUT, Stream<P_OUT>>
        implements Stream<P_OUT>  {
    @Override
    public final <R> R collect(Supplier<R> supplier,
        BiConsumer<R, ? super P_OUT> accumulator,
        BiConsumer<R, R> combiner) {
        return evaluate(ReduceOps.makeRef(supplier, accumulator, combiner));
    }
}

ReduceOps.makeRef 方法解析

   seed : 種子、起源  --- 將初始容器作爲賦值給需要返回的對象state
	accumulator: 蓄電池 : 調用用戶實現的accept方法【theList.add(item)】
	reducer:還原劑;減速器; 調用用戶實現的accept方法【theList.addAll(theList2)】
public static <T, R> TerminalOp<T, R>
    makeRef(Supplier<R> seedFactory,
            BiConsumer<R, ? super T> accumulator,
            BiConsumer<R,R> reducer) {     
        // ReducingSink  Box 兩個內部類  
        class ReducingSink extends Box<R>
                implements AccumulatingSink<T, R, ReducingSink> {
            @Override
            public void begin(long size) {
                state = seedFactory.get();
            }

            @Override
            public void accept(T t) {
                accumulator.accept(state, t);
            }

            @Override
            public void combine(ReducingSink other) {
                reducer.accept(state, other.state);
            }
        }
        return new ReduceOp<T, R, ReducingSink>(StreamShape.REFERENCE) {
            @Override
            public ReducingSink makeSink() {
                return new ReducingSink();
            }
        };
    }

ReduceOps內部類Box

    private static abstract class Box<U> {
    	//最終返回state對象
        U state;
        public U get() { return state; }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章