Java8 List对象中 BigDecimal类型求和

Java8 List对象中 BigDecimal类型求和,第1张

        List集合中的某个对象值是BigDecimal类型的,且需要对所有对象中相同的BigDecimal类型的属性进行求和,找不到现成的工具类可以使用,可以自己来定义一个。

1.定义工具类

package com.kakarote.core.utils;

import lombok.Data;
import lombok.experimental.Accessors;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * JAVA8 分组求和使用方法
 */
public class CollectorsUtils {

    private static final Set CHARACTERISTICS = Collections.emptySet();

    private CollectorsUtils() {
    }

    @SuppressWarnings("unchecked")
    private static  Function check() {
        return i -> (R) i;
    }

    @SuppressWarnings("hiding")
    static class CollectorImpl implements Collector {

        private final Supplier supplier;
        private final BiConsumer accumulator;
        private final BinaryOperator combiner;
        private final Function finisher;
        private final Set characteristics;

        CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Function finisher, Set characteristics) {
            this.supplier = supplier;
            this.accumulator = accumulator;
            this.combiner = combiner;
            this.finisher = finisher;
            this.characteristics = characteristics;
        }

        CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Set characteristics) {
            this(supplier, accumulator, combiner, check(), characteristics);
        }

        @Override
        public Supplier supplier() {
            return supplier;
        }

        @Override
        public BiConsumer accumulator() {
            return accumulator;
        }

        @Override
        public BinaryOperator combiner() {
            return combiner;
        }

        @Override
        public Function finisher() {
            return finisher;
        }

        @Override
        public Set characteristics() {
            return characteristics;
        }
    }

    /**
     * 求和方法
     * @param mapper
     * @param 
     * @return
     */
    public static  Collector summingBigDecimal(ToBigDecimalFunction mapper) {
        return new CollectorImpl<>(
                () -> new BigDecimal[]{new BigDecimal(0)},
                (a, t) -> {
                    a[0] = a[0].add(mapper.applyAsBigDecimal(t), MathContext.DECIMAL32);
                },
                (a, b) -> {
                    a[0] = a[0].add(b[0], MathContext.DECIMAL32);
                    return a;
                },
                a -> a[0], CHARACTERISTICS
        );
    }

    /**
     * 求最大值,这里的最小MIN值,作为初始条件判断值,如果某些数据范围超过百亿,可以根据需求换成 Long.MIN_VALUE 或者 Double.MIN_VALUE
     * @param mapper
     * @param 
     * @return
     */
    public static  Collector maxBy(ToBigDecimalFunction mapper) {
        return new CollectorImpl<>(
                () -> new BigDecimal[]{new BigDecimal(Integer.MIN_VALUE)},
                (a, t) -> {
                    a[0] = a[0].max(mapper.applyAsBigDecimal(t));
                },
                (a, b) -> {
                    a[0] = a[0].max(b[0]);
                    return a;
                },
                a -> a[0], CHARACTERISTICS
        );
    }

    /**
     * 求最小值,这里的最大MAX值,作为初始条件判断值,如果某些数据范围超过百亿,可以根据需求换成 Long.MAX_VALUE 或者 Double.MAX_VALUE
     * @param mapper
     * @param 
     * @return
     */
    public static  Collector minBy(ToBigDecimalFunction mapper) {
        return new CollectorImpl<>(
                () -> new BigDecimal[]{new BigDecimal(Integer.MAX_VALUE)},
                (a, t) -> {
                    a[0] = a[0].min(mapper.applyAsBigDecimal(t));
                },
                (a, b) -> {
                    a[0] = a[0].min(b[0]);
                    return a;
                },
                a -> a[0], CHARACTERISTICS
        );
    }

    /**
     * 求平均,并且保留小数,返回一个平均值
     * @param mapper
     * @param newScale
     * @param roundingMode
     * @param 
     * @return
     */
    public static  Collector averagingBigDecimal(ToBigDecimalFunction mapper,
                                                                      int newScale, int roundingMode) {
        return new CollectorImpl<>(
                () -> new BigDecimal[]{new BigDecimal(0), new BigDecimal(0)},
                (a, t) -> {
                    a[0] = a[0].add(mapper.applyAsBigDecimal(t));
                    a[1] = a[1].add(BigDecimal.ONE);
                },
                (a, b) -> {
                    a[0] = a[0].min(b[0]);
                    return a;
                },
                a -> a[0].divide(a[1], MathContext.DECIMAL32).setScale(newScale, roundingMode), CHARACTERISTICS
        );
    }

    // 自定义函数
    @FunctionalInterface
    interface ToBigDecimalFunction {

        BigDecimal applyAsBigDecimal(T t);

    }

}

2.定义实体类


    @Data
    @Accessors(chain = true) // 开启链式编程
    static class People{
        Long id;
        Integer sex;
        BigDecimal money;
    }

3.测试


    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new People().setId(1l).setSex(1).setMoney(BigDecimal.ONE));
        list.add(new People().setId(2l).setSex(1).setMoney(BigDecimal.TEN));
        list.add(new People().setId(3l).setSex(0).setMoney(BigDecimal.ZERO));
        list.add(new People().setId(4l).setSex(0).setMoney(BigDecimal.TEN));
        list.add(new People().setId(5l).setSex(1).setMoney(BigDecimal.valueOf(5)));
        BigDecimal sum = list.stream().collect(CollectorsUtils.summingBigDecimal(People::getMoney));
        System.out.println("求和:" + sum);
        Map collect = list.stream().collect(Collectors.groupingBy(People::getSex, CollectorsUtils.summingBigDecimal(People::getMoney)));
        System.out.println("分组求和:" + collect);
    }

4.结果

求和:26
分组求和:{0=10, 1=16}

java8listBigDecimal求和

java8lamdba表达式list集合的BigDecimal求和 *** 作

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/792597.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存