List分组求和

list根据某个字段分组,并且统计另一个字段的总和。

可以实现跟MySql的group by一样的效果。

实体类:

import lombok.Data;

@Data
public class CountVO {

    private String name;
    private Long count;

    public CountVO() {
    }

    public CountVO(String name, Long count) {
        this.name = name;
        this.count = count;
    }
}
public class testDemo {
    public static void main(String[] args) {
        List<CountVO> countVOList = new LinkedList<>();
        countVOList.add(new CountVO("苹果",100L,"红富士"));
        countVOList.add(new CountVO("苹果",130L,"金元帅"));
        countVOList.add(new CountVO("香蕉",120L,"芭蕉"));
        countVOList.add(new CountVO("香蕉",130L,"米蕉"));
        countVOList.add(new CountVO("西瓜",140L,"麒麟瓜"));
        countVOList.add(new CountVO("西瓜",120L,"黑金刚"));

        countVOList = countVOList.stream()
                // 根据name分组求和, 返回的是Map
                // CountVO::getName 需要分组的字段
                // Collectors.summingLong(CountVO::getCount)  统计总数
                .collect(Collectors.groupingBy(CountVO::getName, Collectors.summingLong(CountVO::getCount)))
                //转为List集合
                .entrySet().stream()
                .map(e -> new CountVO( e.getKey(),e.getValue()))
                .collect(Collectors.toList());
        System.out.println(JSON.toJSONString(countVOList));
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值