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

    }
相关推荐
好奇的菜鸟1 小时前
如何在IntelliJ IDEA中设置数据库连接全局共享
java·数据库·intellij-idea
DuelCode2 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
优创学社22 小时前
基于springboot的社区生鲜团购系统
java·spring boot·后端
幽络源小助理2 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
猴哥源码2 小时前
基于Java+springboot 的车险理赔信息管理系统
java·spring boot
YuTaoShao3 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
Dcs3 小时前
超强推理不止“大”——手把手教你部署 Mistral Small 3.2 24B 大模型
java
东阳马生架构3 小时前
订单初版—1.分布式订单系统的简要设计文档
java
Code blocks4 小时前
使用Jenkins完成springboot项目快速更新
java·运维·spring boot·后端·jenkins
荔枝吻4 小时前
【沉浸式解决问题】idea开发中mapper类中突然找不到对应实体类
java·intellij-idea·mybatis