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

1    重点

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

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:\java\jdk\jdk9\jdk-9+181_windows-x64_ri\java-se-9-ri\jdk-9\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\java\devolopKit\idea\anZh\IntelliJ IDEA Community Edition 2018.1.4\lib\idea_rt.jar=38089:D:\java\devolopKit\idea\anZh\IntelliJ IDEA Community Edition 2018.1.4\bin" -Dfile.encoding=UTF-8 -classpath "D:\java\devolopKit\idea\anZh\IntelliJ IDEA Community Edition 2018.1.4\lib\idea_rt.jar;D:\java\devolopKit\idea\anZh\IntelliJ IDEA Community Edition 2018.1.4\plugins\junit\lib\junit-rt.jar;D:\java\devolopKit\idea\anZh\IntelliJ IDEA Community Edition 2018.1.4\plugins\junit\lib\junit5-rt.jar;F:\xiangmu3\Xin\test996\target\test-classes;F:\xiangmu3\Xin\test996\target\classes;F:\xiangmu3\Xin\test996\lib\com\google\guava\guava\28.2-jre\guava-28.2-jre.jar;F:\xiangmu3\Xin\test996\lib\com\google\guava\failureaccess\1.0.1\failureaccess-1.0.1.jar;F:\xiangmu3\Xin\test996\lib\com\google\guava\listenablefuture\9999.0-empty-to-avoid-conflict-with-guava\listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar;F:\xiangmu3\Xin\test996\lib\com\google\code\findbugs\jsr305\3.0.2\jsr305-3.0.2.jar;F:\xiangmu3\Xin\test996\lib\org\checkerframework\checker-qual\2.10.0\checker-qual-2.10.0.jar;F:\xiangmu3\Xin\test996\lib\com\google\errorprone\error_prone_annotations\2.3.4\error_prone_annotations-2.3.4.jar;F:\xiangmu3\Xin\test996\lib\com\google\j2objc\j2objc-annotations\1.3\j2objc-annotations-1.3.jar;F:\xiangmu3\Xin\test996\lib\junit\junit\4.12\junit-4.12.jar;F:\xiangmu3\Xin\test996\lib\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;F:\xiangmu3\Xin\test996\lib\com\alibaba\fastjson\1.2.58\fastjson-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

猜你喜欢

转载自www.cnblogs.com/1446358788-qq/p/12664305.html