精华内容
下载资源
问答
  • list.stream().mapToDouble(User::getHeight).sum()//和 list.stream().mapToDouble(User::getHeight).max()//最大 list.stream().mapToDouble(User::getHeight).min...java8 list统计求和、最大、最小、平均) ...

    list.stream().mapToDouble(User::getHeight).sum()//和
    list.stream().mapToDouble(User::getHeight).max()//最大
    list.stream().mapToDouble(User::getHeight).min()//最小
    list.stream().mapToDouble(User::getHeight).average()//平均值

    java8 list统计(求和、最大、最小、平均)

    list.stream().reduce();
    关于reduce可参考:
    https://blog.csdn.net/weixin_43860260/article/details/94875064

    展开全文
  • list.stream().mapToDouble(User::getHeight).sum()//和 list.stream().mapToDouble(User::getHeight).max()//最大 list.stream().mapToDouble(User::getHeight).min()//最小 list.stream().mapToDouble(User::...
  • java8 list BigDecimal 求和

    千次阅读 2021-04-15 15:22:16
    jdk1.8 list BigDecimal 求和 自定义一个新的list对BigDecimal求和的工具类,封装求和,最大值,最小值,平均值 下面有贴代码出来 ...使用自定义的CollectorsUtil类进行list求和 ArrayList<Test>

    自定义一个新的list对BigDecimal求和的工具类,封装求和,最大值,最小值,平均值
    下面有贴代码出来

    //测试数据类
    @Data
    @Accessors(chain = true) //开启链式编程
    static class Test{
        Long id;
        Integer type;
        BigDecimal money;
    }
    

    使用自定义的CollectorsUtil类进行list求和

    ArrayList<Test> list = Lists.newArrayList(
    	new Test().setId(1L).setType(1).setMoney(BigDecimal.ONE),
    	new Test().setId(1L).setType(2).setMoney(BigDecimal.TEN),
    	new Test().setId(1L).setType(1).setMoney(BigDecimal.ZERO),
    	new Test().setId(1L).setType(2).setMoney(BigDecimal.ONE),
    	new Test().setId(1L).setType(3).setMoney(BigDecimal.valueOf(5))
            );
    BigDecimal collect = list.stream().collect(CollectorsUtil.summingBigDecimal(Test::getMoney));
    System.out.println("collect = " + collect);
    //运行结果 collect = 17
    

    使用自定义的CollectorsUtil类进行list分组求和

    Map<Integer, BigDecimal> collect1 = list.stream().collect(Collectors.groupingBy(Test::getType, CollectorsUtil.summingBigDecimal(Test::getMoney)));
    System.out.println("collect1 = " + collect1);
    //运行结果 collect = {1=1, 2=11, 3=5}
    
    import com.nanase.takeshi.annotion.ToBigDecimalFunction;
    
    import java.math.BigDecimal;
    import java.math.MathContext;
    import java.util.Collections;
    import java.util.Set;
    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;
    
    /**
     * JAVA8 分组求和要用到的
     * 使用方法
     * list.stream().collect(Collectors.groupingBy(Entry::getName, CollectorsUtil.summingBigDecimal(Entry::getValue)));
     * list.stream().collect(CollectorsUtil.summingBigDecimal(Entry::getValue));
     * CollectorsUtil
     *
     * @author 725
     * @date 2020/12/31 16:25
     */
    public class CollectorsUtil {
    
        private static final Set<Collector.Characteristics> CHARACTERISTICS = Collections.emptySet();
    
        private CollectorsUtil() {
        }
    
        @SuppressWarnings("unchecked")
        private static <I, R> Function<I, R> castingIdentity() {
            return i -> (R) i;
        }
    
        /**
         * Simple implementation class for {@code Collector}.
         *
         * @param <T> the type of elements to be collected
         * @param <R> the type of the result
         */
        @SuppressWarnings("hiding")
        static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
            private final Supplier<A> supplier;
            private final BiConsumer<A, T> accumulator;
            private final BinaryOperator<A> combiner;
            private final Function<A, R> finisher;
            private final Set<Characteristics> characteristics;
    
            CollectorImpl(Supplier<A> supplier,
                          BiConsumer<A, T> accumulator,
                          BinaryOperator<A> combiner,
                          Function<A, R> finisher,
                          Set<Characteristics> characteristics) {
                this.supplier = supplier;
                this.accumulator = accumulator;
                this.combiner = combiner;
                this.finisher = finisher;
                this.characteristics = characteristics;
            }
    
            CollectorImpl(Supplier<A> supplier,
                          BiConsumer<A, T> accumulator,
                          BinaryOperator<A> combiner,
                          Set<Characteristics> characteristics) {
                this(supplier, accumulator, combiner, castingIdentity(), characteristics);
            }
    
            @Override
            public BiConsumer<A, T> accumulator() {
                return accumulator;
            }
    
            @Override
            public Supplier<A> supplier() {
                return supplier;
            }
    
            @Override
            public BinaryOperator<A> combiner() {
                return combiner;
            }
    
            @Override
            public Function<A, R> finisher() {
                return finisher;
            }
    
            @Override
            public Set<Characteristics> characteristics() {
                return characteristics;
            }
        }
    
        /**
         * 求和方法
         *
         * @param mapper
         * @param <T>
         * @return
         */
        public static <T> Collector<T, ?, BigDecimal> summingBigDecimal(ToBigDecimalFunction<? super T> 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 <T>
         * @return
         */
        public static <T> Collector<T, ?, BigDecimal> maxBy(ToBigDecimalFunction<? super T> 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 <T>
         * @return
         */
        public static <T> Collector<T, ?, BigDecimal> minBy(ToBigDecimalFunction<? super T> 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 newScale     保留小数位数
         * @param roundingMode 小数处理方式
         *                     #ROUND_UP 进1
         *                     #ROUND_DOWN 退1
         *                     #ROUND_CEILING  进1截取:正数则ROUND_UP,负数则ROUND_DOWN
         *                     #ROUND_FLOOR  退1截取:正数则ROUND_DOWN,负数则ROUND_UP
         *                     #ROUND_HALF_UP >=0.5进1
         *                     #ROUND_HALF_DOWN >0.5进1
         *                     #ROUND_HALF_EVEN
         *                     #ROUND_UNNECESSARY
         */
        public static <T> Collector<T, ?, BigDecimal> averagingBigDecimal(ToBigDecimalFunction<? super T> 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].add(b[0]);
                        return a;
                    },
                    a -> a[0].divide(a[1], MathContext.DECIMAL32).setScale(newScale, roundingMode), CHARACTERISTICS);
        }
    
    }
    
    
    展开全文
  • JAVA8 ARRAY、LIST操作 汇【5】)- JAVA8 LAMBDA LIST统计求和、最大、最小、平均) public class Apple { private Integer id; private String name; private BigDecimal money; private Integer num; ...

    JAVA8 ARRAY、LIST操作 汇【5】)- JAVA8 LAMBDA LIST统计(求和、最大、最小、平均)

    复制代码

    public class Apple {
        private Integer id;
        private String name;
        private BigDecimal money;
        private Integer num;
        public Apple(Integer id, String name, BigDecimal money, Integer num) {
            this.id = id;
            this.name = name;
            this.money = money;
            this.num = num;
        }
    }

    复制代码

     

    复制代码

    List<Apple> appleList = new ArrayList<>();//存放apple对象集合
    
    Apple apple1 =  new Apple(1,"苹果1",new BigDecimal("3.25"),10);
    Apple apple12 = new Apple(1,"苹果2",new BigDecimal("1.35"),20);
    Apple apple2 =  new Apple(2,"香蕉",new BigDecimal("2.89"),30);
    Apple apple3 =  new Apple(3,"荔枝",new BigDecimal("9.99"),40);
    
    appleList.add(apple1);
    appleList.add(apple12);
    appleList.add(apple2);
    appleList.add(apple3);

    复制代码

     

     
    list.stream().mapToDouble(User::getHeight).sum()//和
    list.stream().mapToDouble(User::getHeight).max()//最大
    list.stream().mapToDouble(User::getHeight).min()//最小
    list.stream().mapToDouble(User::getHeight).average()//平均值
     

     

    复制代码

    1. List转Map
    id为key,apple对象为value,可以这么做:
    /**
     * List -> Map
     * 需要注意的是:
     * toMap 如果集合对象有重复的key,会报错Duplicate key ....
     *  apple1,apple12的id都为1。
     *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
     */
    Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
    打印appleMap:
    {1=Apple{id=1, name='苹果1', money=3.25, num=10}, 2=Apple{id=2, name='香蕉', money=2.89, num=30}, 3=Apple{id=3, name='荔枝', money=9.99, num=40}}

    复制代码

     

    复制代码

     2. 分组
     List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
    //List 以ID分组 Map<Integer,List<Apple>>
    Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
    
    System.err.println("groupBy:"+groupBy);
    {1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}

    复制代码

     

    3. 过滤filter: 从集合中过滤出来符合条件的元素(map只是覆盖属性,filter根据判断属性来collect宿主bean):
    //过滤出符合条件的数据
    List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
    
    System.err.println("filterList:"+filterList);
    [Apple{id=2, name='香蕉', money=2.89, num=30}]

     

     

    复制代码

    4. 求和: 将集合中的数据按照某个属性求和:
    BigDecimal:
    //计算 总金额
    BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
    System.err.println("totalMoney:"+totalMoney); //totalMoney:17.48
    
    Integer:
    //计算 数量
    int sum = appleList.stream().mapToInt(Apple::getNum).sum();
    System.err.println("sum:"+sum); //sum:100
    
    List<Integer> cc = new ArrayList<>();
    cc.add(1);cc.add(2);cc.add(3);
    int sum = cc.stream().mapToInt(Integer::intValue).sum();//6

    复制代码

     

     

    复制代码

    ★5    Collectors.groupingBy进行分组、排序等操作:
    import javaX.Model.Student;
    
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    public class FunctionX {
        public static void main(String[] args) {
            //1.分组计数
            List<Student> list1= Arrays.asList(new Student(1,"one","zhao"),new Student(2,"one","qian"),new Student(3,"two","sun"));
            //1.1根据某个属性分组计数
            Map<String,Long> result1=list1.stream().collect(Collectors.groupingBy(Student::getGroupId,Collectors.counting()));
            System.out.println(result1);
            //1.2根据整个实体对象分组计数,当其为String时常使用
            Map<Student,Long> result2=list1.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
            System.out.println(result2);
            //1.3根据分组的key值对结果进行排序、放进另一个map中并输出
            Map<String,Long> xMap=new HashMap<>();
            result1.entrySet().stream().sorted(Map.Entry.<String,Long>comparingByKey().reversed()) //reversed不生效
                    .forEachOrdered(x->xMap.put(x.getKey(),x.getValue()));
            System.out.println(xMap);
    
            //2.分组,并统计其中一个属性值得sum或者avg:id总和
            Map<String,Integer> result3=list1.stream().collect(
                    Collectors.groupingBy(Student::getGroupId,Collectors.summingInt(Student::getId))
            );
            System.out.println(result3);
    
        }
    }
    展开全文
  • list的数据按某些属性进行分组,然后对组内某些属性求和,类似sql的group by功能。 例如以下以机构和客户号组合分组,对debt求和,最后形成一个新的list public static void main(String[] args) { DebtCust ...

    对list的数据按某些属性进行分组,然后对组内某些属性求和,类似sql的group by功能。

    例如以下以机构和客户号组合分组,对debt求和,最后形成一个新的list 

     public static void main(String[] args) {
            DebtCust d1 = new DebtCust().setDeptId(1L).setCustCode("1").setDebt(new BigDecimal("5.1"));
            DebtCust d2 = new DebtCust().setDeptId(2L).setCustCode("2").setDebt(new BigDecimal("5.1"));
            DebtCust d3 = new DebtCust().setDeptId(1L).setCustCode("1").setDebt(new BigDecimal("5.0"));
            DebtCust d4 = new DebtCust().setDeptId(3L).setCustCode("1").setDebt(new BigDecimal("5.0"));
            DebtCust d5 = new DebtCust().setDeptId(2L).setCustCode("2").setDebt(new BigDecimal("5.1"));
            List<DebtCust> debtCustList = Arrays.asList(new DebtCust[]{d1, d2, d3, d4, d5});
            List<DebtCust> newList = new ArrayList<>();
            debtCustList.parallelStream().collect(Collectors.groupingBy(d -> d.getDeptId() + d.getCustCode(), Collectors.toList()))
                    .forEach((id, groupList) -> {
                        groupList.stream().reduce(
                                (a, b) -> new DebtCust()
                                                .setDeptId(a.getDeptId())
                                                .setCustCode(a.getCustCode())
                                                .setDebt(a.getDebt().add(b.getDebt()))
                        ).ifPresent(newList::add);
                    });
            System.out.println(newList);
        }

    tips:本方法仅适用大数据量统计(不适用于超大对象,例如list长度100w)

    记录下看到的金句:买好的,不如买得好,买得好不如卖得巧。

    所谓的价值投资,依然离不开择时,不得不承认择时是困难的,专业的芒格巴菲等智者也有失误的时候,所以,不轻易择时。

    展开全文
  • list.stream().mapToDouble(User::getHeight).sum()//和 list.stream().mapToDouble(User::getHeight).max()//最大 list.stream().mapToDouble(User::getHeight).min()//最小 list.stream().mapToDouble(User::...
  • 对集合数据的统计,是开发中常用的功能,掌握好Java Stream提供的方法,避免自己写代码统计,可以提高工作效率。 先造点数据: pigs.add(new Pig(1, "猪爸爸", 31, "M", false)); pigs.add(new Pig(2, "猪妈妈", 28,...
  • import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class FunctionX { public static void main(String[] args) { //1.分组计数 ...
  • 上面导出excel后,需要在文档数据末尾新增一行合计,页面的合计是前端自动计算的,导出时候试了下poi,以失败告终,于是就统计数据集合,然后把统计后的值add到list中去,当作数据一并导出。 由于我这个Map里面有25...
  • list求和 list.stream().mapToDouble(User::getHeight).sum()//和 list.stream().mapToDouble(User::getHeight).max()//最大 list.stream().mapToDouble(User::getHeight).min()//最小 list.stream().mapToDouble...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 8,446
精华内容 3,378
关键字:

java统计list求和

java 订阅