Java8 Stream根据某字段分组统计

一:多字段分组统计

方法一

public static void main(String[] args) {
        List list = new ArrayList<>();
        for(int i = 0; i< 5; i++){
            Test test = new Test();
            //主键id
            test.setId(Long.valueOf(i));
            //金额
            test.setMoney(new BigDecimal(i));
            //数量
            test.setCount(new BigDecimal(i));
            list.add(test);
        }
        for(int i = 0; i< 2; i++){
            Test test = new Test();
            //主键id
            test.setId(Long.valueOf(i));
            //金额
            test.setMoney(new BigDecimal(i));
            //数量
            test.setCount(new BigDecimal(i));
            list.add(test);
        }
        List resultList = new ArrayList<>();
        //先根据id分组
        Map> map = list.stream().collect(Collectors.groupingBy(m->m.getId()));
        //分组后求 总金额,总数量
        map.keySet().stream().forEach(key->{
            Test info = new Test();
            List listInfo = map.get(key);
            //总金额
            BigDecimal sumMoney = listInfo.stream().map(Test::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            //总数量
            BigDecimal sumCount = listInfo.stream().map(Test::getCount).reduce(BigDecimal.ZERO,BigDecimal::add);
            info.setId(key);
            info.setMoney(sumMoney);
            info.setCount(sumCount);
            resultList.add(info);
        });
        System.out.println(resultList);
    }

方法二

List collect = stus.stream().collect(Collectors.toMap(k ->k.getId()+k.getBj(), e -> e, (o1, o2) -> {
            o1.setK0qmkcje((null==o1.getK0qmkcje()?BigDecimal.ZERO:o1.getK0qmkcje()).add((null==o2.getK0qmkcje()?BigDecimal.ZERO:o2.getK0qmkcje())).setScale(0,BigDecimal.ROUND_HALF_UP));
            return o1;
        })).values().stream().collect(Collectors.toList());

获取此类格式数据 Map

public static void main(String[] args) {
   Map ageGroup = list.stream().collect(Collectors.groupingBy(Student::getName
            , Collectors.collectingAndThen(Collectors.toList()
                    , x -> x.stream().map(Student::getStature).reduce(BigDecimal.ZERO, BigDecimal::add))));
   
}

public static void main(String[] args) {
    Map ageGroup = list.stream().collect(Collectors.groupingBy(Student::getName
            , MyCollector.summingDecimal(Student::getStature)));
    System.out.println(ageGroup);
}

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