reduce函数

2022-12-28  本文已影响0人  程序男保姆
    /** ============================ reduce函数 ============================== */
 
    /**
     * reduce有三类, 分别是一个参数, 两个参数, 三个参数
     * 1、两个参数较一个参数多了一个初始值
     * 2、三个参数较两个参数多了一个并行操作时用于合并操作的函数时接口对象, 因此当串行操作时与两个参数的效果一致
     */
 
    // 一个参数
    @Test
    public void testReduce1() {
        List<Integer> list = Arrays.asList(3, 2, 4, 1);
        System.out.println(list.stream().reduce((acc, tmp) -> acc + tmp).get());
    }
 
    // 两个参数
    @Test
    public void testReduce2() {
        List<Integer> list = Arrays.asList(3, 2, 4, 1);
        System.out.println(list.stream().reduce(100, (acc, tmp) -> acc + tmp).intValue());
    }
 
    // 三个参数
    @Test
    public void testReduce3() {
        // 串行操作
        List<Integer> list = Arrays.asList(3, 2, 4, 1);
        System.out.println(list.stream().reduce(100
                , (acc, tmp) -> acc + tmp
                , (a, b) -> a + b).intValue());  // out ==> 110
 
        // 并行操作
        System.out.println(list.stream().parallel().reduce(100
                , (acc, tmp) -> acc + tmp
                , (a, b) -> a + b).intValue());  // out ==> 410
        /**
         * 分析:
         * list集合中四个值并行执行, 分别与初始值100相加后, 再进行合并操作, 即:
         * 1)3+100=103, 2+100=102, 4+100=104, 1+100=101
         * 2)103+102+104+101=410
         */
    }

       三个参数  1。 初始值 ;2。 转换的值; 3。 1+2
       Collectors.reducing(BigDecimal.ZERO, a -> a.getTotalAmount(), (a, b) -> a.add(b))

上一篇 下一篇

猜你喜欢

热点阅读