• 高效 告别996,开启java高效编程之门 3-3实战:利用Lambda+Stream处理业务逻辑


    1    重点

    1.1    本节目的

    仅仅为了展示Stream流操作集合的便利性,看看demo就好,后边他大爷的还继续讲。

    1.2    对以下方法的应用(这是本人对留的方法的理解,有不对的地方,欢迎大家指正)

    Stream.peek:    对流的操作,不操作流,不执行

    Returns a stream consisting of the elements of this stream, truncated  to be no longer than {@code maxSize} in length.

    <p>This is a <a href="package-summary.html#StreamOps">short-circuiting stateful intermediate operation</a>.

    Collection.stream   建立流

    Returns a sequential

    Stream.filter     筛选出结构一致的集合

    Returns a stream consisting of the results of applying the given function to the elements of this stream.

    Stream.limit(n)  取出前n条

    Stream.map    返回新的流(结构可能不一致)

    @return the new stream

      

    Stream.collect   返回可操作的集合

    @return an {@code Optional} describing the minimum element of this stream, * or an empty {@code Optional} if the stream is empty

     

     

    2    代码演练

    需求:

     根据第一章需求,女盆友提出需求
    * 1 打印所有商品
    * 2 图书类的商品一定给买
    * 3 最贵的买两件
    * 4 打印最贵的两件商品的名称和总价


    测试类:

    package com.imooc.zhangxiaoxi.stream;
    
    import com.alibaba.fastjson.JSON;
    import com.imooc.zhangxiaoxi.lambda.cart.CartService;
    import com.imooc.zhangxiaoxi.lambda.cart.Sku;
    import com.imooc.zhangxiaoxi.lambda.cart.SkuCategoryEnum;
    import org.junit.Test;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.List;
    import java.util.concurrent.atomic.AtomicReference;
    import java.util.stream.Collectors;
    
    /**
     * StreamVs
     *
     * @author 魏豆豆
     * @date 2020/4/7
     */
    public class StreamVs {
    
        /**
         * 流和普通方法对比,本节应用普通方法
         *
         * 根据第一章需求,女盆友提出需求
         * 1    打印所有商品
         * 2    图书类的商品一定给买
         * 3    最贵的买两件
         * 4    打印最贵的两件商品的名称和总价
         */
    
        /**
         * 普通方法
         */
       /* @Test
        public void oldCartHandle(){
            //1 打印所有商品
            List<Sku> skuList = CartService.getSkuList();
            System.out.println("====================================================================================================");
            for(Sku sku: skuList){
                System.out.println(JSON.toJSONString(sku,true));
            }
    
    
            //2 排除图书类
            List<Sku> skuListNoBooks = new ArrayList<Sku>();
            for(Sku sku:skuList){
                if(!sku.getSkuCategory().equals(SkuCategoryEnum.BOOKS)){
                    skuListNoBooks.add(sku);
                }
            }
    
            //3 最贵的买两件
            skuListNoBooks.sort(new Comparator<Sku>() {
                @Override
                public int compare(Sku o1, Sku o2) {
                    if(o1.getTotalPrice()> o2.getTotalPrice()){
                        return -1;
                    }else if(o1.getTotalPrice() < o2.getTotalPrice()){
                        return 1;
                    }else{
                        return 0;
                    }
                }
            });
    
            List<Sku> skuListPreTwo = new ArrayList<Sku>();
            for(int i = 0;i<2;i++){
                skuListPreTwo.add(skuListNoBooks.get(i));
            }
    
            System.out.println("====================================================================================================");
            Double totalPrice = 0.0;
            for(Sku sku:skuListPreTwo){
                totalPrice+=sku.getTotalPrice();
            }
    
            List<String> skuNameList = new ArrayList<String>();
            for (Sku sku:skuListPreTwo){
                skuNameList.add(sku.getSkuName());
            }
    
    
            System.out.println("商品总价为:"+totalPrice);
            System.out.println("商品名称为:"+ JSON.toJSONString(skuNameList,true));
        }*/
    
        @Test
        /**
         * 使用Stream流的方式来实现需求:
         */
        public void newCartHandler(){
    
            //定义  原子引用类,可以保你多线程 安全,防止多线程 计数冲突
            AtomicReference<Double> money = new AtomicReference<>(Double.valueOf(0.0));
    
            List<String> skuNameList =
            CartService.getSkuList()
                    /**
                     * 1    建立stream流
                     */
                    .stream()
                    /**
                     * 2    打印所有商品的信息
                     */
                    .peek(sku -> System.out.println(JSON.toJSONString(sku,true)))
                    /**
                     * 3    筛选出非图书类
                     */
                    .filter(sku -> !sku.getSkuCategory().equals(SkuCategoryEnum.BOOKS))
                    /**
                     * 4    按照价格排序(使用方法引用)
                     * reversed排序反转 从大到小
                     */
                    .sorted(Comparator.comparing(Sku::getTotalPrice).reversed())
                    /**
                     * 5    取出前两条
                     */
                    .limit(3)
                    /**
                     * 6    累加商品总金额
                     */
                    .peek(sku -> {money.set(money.get()+sku.getTotalPrice());})
                    /**
                     * 7    取出商品名称集合
                     */
                    .map(sku -> sku.getSkuName())
                    /**
                     * 8    收集结果
                     */
                    .collect(Collectors.toList());
    
                    //因为money是get类型,需要get一下值
                    System.out.println("商品总价为:"+money.get());
                    System.out.println("商品名称为:"+ JSON.toJSONString(skuNameList,true));
        }
    
    
    }

    其他类参考2-3:

    打印日志:

    D:javajdkjdk9jdk-9+181_windows-x64_rijava-se-9-rijdk-9injava.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:javadevolopKitideaanZhIntelliJ IDEA Community Edition 2018.1.4libidea_rt.jar=38089:D:javadevolopKitideaanZhIntelliJ IDEA Community Edition 2018.1.4in" -Dfile.encoding=UTF-8 -classpath "D:javadevolopKitideaanZhIntelliJ IDEA Community Edition 2018.1.4libidea_rt.jar;D:javadevolopKitideaanZhIntelliJ IDEA Community Edition 2018.1.4pluginsjunitlibjunit-rt.jar;D:javadevolopKitideaanZhIntelliJ IDEA Community Edition 2018.1.4pluginsjunitlibjunit5-rt.jar;F:xiangmu3Xin	est996	arget	est-classes;F:xiangmu3Xin	est996	argetclasses;F:xiangmu3Xin	est996libcomgoogleguavaguava28.2-jreguava-28.2-jre.jar;F:xiangmu3Xin	est996libcomgoogleguavafailureaccess1.0.1failureaccess-1.0.1.jar;F:xiangmu3Xin	est996libcomgoogleguavalistenablefuture9999.0-empty-to-avoid-conflict-with-guavalistenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar;F:xiangmu3Xin	est996libcomgooglecodefindbugsjsr3053.0.2jsr305-3.0.2.jar;F:xiangmu3Xin	est996liborgcheckerframeworkchecker-qual2.10.0checker-qual-2.10.0.jar;F:xiangmu3Xin	est996libcomgoogleerrorproneerror_prone_annotations2.3.4error_prone_annotations-2.3.4.jar;F:xiangmu3Xin	est996libcomgooglej2objcj2objc-annotations1.3j2objc-annotations-1.3.jar;F:xiangmu3Xin	est996libjunitjunit4.12junit-4.12.jar;F:xiangmu3Xin	est996liborghamcresthamcrest-core1.3hamcrest-core-1.3.jar;F:xiangmu3Xin	est996libcomalibabafastjson1.2.58fastjson-1.2.58.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit3 com.imooc.zhangxiaoxi.stream.StreamVs,newCartHandler
    {
        "skuCategory":"ELECTRONICS",
        "skuId":2020001,
        "skuName":"无人机",
        "skuPrice":999.0,
        "totalNum":1,
        "totalPrice":999.0
    }
    {
        "skuCategory":"CLOTHING",
        "skuId":2020002,
        "skuName":"T-shirt",
        "skuPrice":50.0,
        "totalNum":2,
        "totalPrice":100.0
    }
    {
        "skuCategory":"BOOKS",
        "skuId":2020003,
        "skuName":"人生的枷锁",
        "skuPrice":30.0,
        "totalNum":1,
        "totalPrice":30.0
    }
    {
        "skuCategory":"BOOKS",
        "skuId":2020004,
        "skuName":"老人与海",
        "skuPrice":20.0,
        "totalNum":1,
        "totalPrice":20.0
    }
    {
        "skuCategory":"BOOKS",
        "skuId":2020005,
        "skuName":"剑指高效编程",
        "skuPrice":288.0,
        "totalNum":1,
        "totalPrice":288.0
    }
    {
        "skuCategory":"CLOTHING",
        "skuId":2020006,
        "skuName":"大头皮鞋",
        "skuPrice":300.0,
        "totalNum":1,
        "totalPrice":300.0
    }
    {
        "skuCategory":"SPROTS",
        "skuId":2020007,
        "skuName":"杠铃",
        "skuPrice":2000.0,
        "totalNum":1,
        "totalPrice":2000.0
    }
    {
        "skuCategory":"ELECTRONICS",
        "skuId":2020008,
        "skuName":"ThinkPad",
        "skuPrice":5000.0,
        "totalNum":1,
        "totalPrice":5000.0
    }
    商品总价为:7999.0
    商品名称为:[
        "ThinkPad",
        "杠铃",
        "无人机"
    ]
    
    Process finished with exit code 0
  • 相关阅读:
    杂项收集,包括-发邮件、二维码生成、文件下载、压缩、导出excel
    SQL2008删除大量数据
    优秀程序设计的18大原则
    多线程基础
    SQL金典
    [读书笔记]高效程序员的45个习惯:敏捷开发修炼之道
    Unity 查找资源引用工具
    Unity自动生成各种机型分辨率效果工具
    Unity Editor模式 Invoke()函数 失效
    Unity 特效 粒子 自动播放
  • 原文地址:https://www.cnblogs.com/1446358788-qq/p/12664305.html
Copyright © 2020-2023  润新知