stream中reduce使用

1.reduce为终端操作,可以对中间操作筛选出来的流数据作出一系列的加减乘除等操作。

package com.qingfeng.stream;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class streamTest02 {
    public static void main(String[] args) {

        //stream流重载了reduce方法,含三个
        // 1.T reduce(T identity,BinaryOperator accumulator)
        //参数一为累加器的函数的标识,参数二为函数(+,-,*,/)
        //2.Optional reduce(BinaryOperator accumulator)
        //3. U reduce(U identity,BiFunction accumulator,BinaryOperator combiner)

        List<BigDecimal> list = new ArrayList<>();
        BigDecimal a = new BigDecimal("10");
        list.add(a);
        BigDecimal b = new BigDecimal("20");
        list.add(b);
        BigDecimal c = new BigDecimal("30");
        list.add(c);
        BigDecimal d = new BigDecimal("-10");
        list.add(d);

        //BigDecimal.ZERO为0,以0为底数和流里的每一个元素相加
        //求和
        BigDecimal result = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);//结果为50
        System.out.println(result);
        //亦可写作
        BigDecimal result1 = list.stream().reduce(BigDecimal.ZERO, (x,y) -> x.add(y));//结果为50
        System.out.println(result1);

        //求最大值
        Optional<BigDecimal> max = list.stream().reduce(BigDecimal::max);//结果为30
        System.out.println(max.get());

        //求最小值
        Optional<BigDecimal> min = list.stream().reduce(BigDecimal::min);//结果为-10
        System.out.println(min.get());

        //各项相乘
        Optional<BigDecimal> mu = list.stream().reduce(BigDecimal::multiply);//结果为-60000
        System.out.println(mu.get());
    }
}
            List<SysUserPojo> flist = userDao.selectAllsUser(sysUserPojo);
            List<BigDecimal> list1= new ArrayList<>();
            for (SysUserPojo userPojo : flist) {
                List<TransactionCurrencyPojo> list = transactionCurrencyDao.selectMingCount(userPojo.getId());
                for (TransactionCurrencyPojo transactionCurrencyPojo : list) {
                    list1.add(transactionCurrencyPojo.getAmount());
                }
                BigDecimal result = list1.stream()
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                 userPojo.setMadCount(result);
                 list1.clear();
            }

你可能感兴趣的:(java,开发语言)