编程语言
首页 > 编程语言> > java-lambda源码走读

java-lambda源码走读

作者:互联网

一、需要走读的代码

        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple(1, "青色"));
        appleList.add(new Apple(2, "橙色"));
        appleList.add(new Apple(3, "红色"));
        appleList.add(new Apple(4, "绿色"));
        appleList.add(new Apple(5, "绿色"));
        appleList.add(new Apple(6, "紫色"));

        Stream<Apple> stream = appleList.stream();
        // 筛选颜色是绿色的苹果
        Stream<Apple> appleStream = stream.filter(item -> "绿色".equals(item.getColor()));
        // 苹果 -> 数字(苹果的重量)
        Stream<Integer> integerStream = appleStream.map(item -> item.getWeight());
        // 将苹果的重量数据收集起来
        List<Integer> collect = integerStream.collect(Collectors.toList());

        System.out.println(collect);

流程概述:

1,数据源.stream()方法:返回head(PipeLine,depth=0);

2,head.filter()方法:返回filterOp(PipeLine/StatelessOp,depth=1),并让head向下绑定filterOp,让filterOp向上绑定head;

3,filterOp.map()方法:返回mapOp(PipeLine/StatelessOp,depth=2),并让filterOp向下绑定mapOp,让mapOp向上绑定filterOp;

4,mapOp.collect方法:

  4.1,生成collectOp(TerminalOp),终结操作对象;

  4.2,使用collectOp,生成collectSink(Sink);

  4.2,以mapOp为起始点,向前遍历双向链表,条件为depth > 0:

     cycle1:执行mapOp.opWrapSink方法,生成mapSink(Sink),并让mapSink向下绑定collectSink;

     cycle2:执行filterOp.opWrapSink方法,生成filterSink(Sink),并让filterSink向下绑定mapSink;

  4.3,执行filterSink.begin方法

     -- 执行filterSink下一个sink(mapSink)的begin方法

                --执行mapSink下一个sink(collectSink)的begin方法,使collectSink的state = supplier<T>中的T,Collectors.toList()使这个T为new list

  4.4,执行数据源.forEachRemaining(filterSink)方法,循环遍历数据源的每个元素

    -- 执行filteSink.accept(数据源的元素)方法,如果符合断言(Predicate),则进入下一环节

      -- 执行filterSink下一个sink(mapSink)的accept(数据源的元素)方法,将map(Function)后的结果传入mapSink下一个sink(collectSink)的accept方法

        -- collectSink的accept方法使用BiConsumer将传入的结果放入步骤4.3中的新list中

  4.5,返回collectSink.get(),是个supplier,返回步骤4.3中的list


二、从Head开始

Stream<Apple> stream = appleList.stream();

 

 

 

 

 

 

 三、走向下一个filter节点

Stream<Apple> appleStream = stream.filter(item -> "绿色".equals(item.getColor()));

 

四、走向下一个map节点

Stream<Integer> integerStream = appleStream.map(item -> item.getWeight());

 

五,收尾

List<Integer> collect = integerStream.collect(Collectors.toList());

 

 

 

 

 

 

 

 

 

 

 

  

标签:collectSink,appleList,java,stream,走读,item,源码,new,filterOp
来源: https://www.cnblogs.com/seeall/p/16427621.html