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));

    }
相关推荐
WZTTMoon32 分钟前
Spring Boot 启动全解析:4 大关键动作 + 底层逻辑
java·spring boot·后端
章鱼哥73033 分钟前
[特殊字符] SpringBoot 自定义系统健康检测:数据库、Redis、表统计、更新时长、系统性能全链路监控
java·数据库·redis
深圳佛手41 分钟前
Sharding-JDBC 和 Sharding-Proxy 区别
java
kk哥88991 小时前
inout参数传递机制的底层原理是什么?
java·开发语言
小二·1 小时前
Spring框架入门:深入理解Spring DI的注入方式
java·后端·spring
避避风港1 小时前
转发与重定向
java·servlet
毕设源码-钟学长2 小时前
【开题答辩全过程】以 基于springboot和协同过滤算法的线上点餐系统为例,包含答辩的问题和答案
java·spring boot·后端
q***44152 小时前
Spring Security 新版本配置
java·后端·spring
o***74172 小时前
Springboot中SLF4J详解
java·spring boot·后端