Java8新特性整理记录

1、list实体集合根据某个属性分组后求和

方法一:

java 复制代码
list.stream().collect(Collectors.groupingBy(e -> e.getId())).values().stream().map(d -> {
            DemoEntity sampleData = d.get(0);
            sampleData.setPremium(d.stream().map(s -> new BigDecimal(s.getPremium())).reduce(BigDecimal.ZERO, BigDecimal::add).longValue());
            return sampleData;
        }).collect(Collectors.toList());

方法二:

复制代码
List orderTwo = list.stream().collect(Collectors.toMap(DemoEntity::getId,e->e,(o1,o2)->{
            o1.setPremium(o1.getPremium()+o2.getPremium());
            return o1;
        })).values().stream().collect(Collectors.toList());
        System.out.println(JSON.toJSON(orderTwo));

例子:

java 复制代码
@Data
public class DemoEntity {

    private int id;
    private Long premium;
}

运行main方法
public static void main(String[] args) {
        List<DemoEntity> list = new ArrayList<>();
        DemoEntity demo = new DemoEntity();
        demo.setId(1);
        demo.setPremium(23L);
        DemoEntity demo1 = new DemoEntity();
        demo1.setId(2);
        demo1.setPremium(13L);
        list.add(demo);
        list.add(demo1);

        List<DemoEntity> list1 = new ArrayList<>();
        DemoEntity demo4 = new DemoEntity();
        demo4.setId(1);
        demo4.setPremium(12L);
        DemoEntity demo5 = new DemoEntity();
        demo5.setId(2);
        demo5.setPremium(45L);
        list1.add(demo4);
        list1.add(demo5);
        
        list.addAll(list1);
        System.out.println(JSON.toJSON(list));

        List orders = list.stream().collect(Collectors.groupingBy(e -> e.getId())).values().stream().map(d -> {
            DemoEntity sampleData = d.get(0);
            sampleData.setPremium(d.stream().map(s -> new BigDecimal(s.getPremium())).reduce(BigDecimal.ZERO, BigDecimal::add).longValue());
            return sampleData;
        }).collect(Collectors.toList());
        System.out.println(JSON.toJSON(orders));

       List orderTwo = list.stream().collect(Collectors.toMap(DemoEntity::getId,e->e,(o1,o2)->{
            o1.setPremium(o1.getPremium()+o2.getPremium());
            return o1;
        })).values().stream().collect(Collectors.toList());
        System.out.println(JSON.toJSON(orderTwo));

    }
相关推荐
程序员阿鹏7 分钟前
责任链模式
java·spring·servlet·tomcat·maven·责任链模式
@淡 定17 分钟前
Java内存模型(JMM)详解
java·开发语言
czhc114007566341 分钟前
C# 1221
java·servlet·c#
黄俊懿43 分钟前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——全局事务的回滚
java·后端·spring·spring cloud·微服务·架构·架构师
派大鑫wink1 小时前
【Day12】String 类详解:不可变性、常用方法与字符串拼接优化
java·开发语言
JIngJaneIL1 小时前
基于springboot + vue健康管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
秋饼1 小时前
【三大锁王争霸赛:Java锁、数据库锁、分布式锁谁是卷王?】
java·数据库·分布式
电商API&Tina1 小时前
【电商API接口】关于电商数据采集相关行业
java·python·oracle·django·sqlite·json·php
刘一说1 小时前
Spring Boot中IoC(控制反转)深度解析:从实现机制到项目实战
java·spring boot·后端
悟空码字1 小时前
SpringBoot参数配置:一场“我说了算”的奇幻之旅
java·spring boot·后端