ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-lambda源码走读

2022-07-01 15:34:29  阅读:119  来源: 互联网

标签:collectSink appleList java stream 走读 item 源码 new filterOp


一、需要走读的代码

        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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有