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

    }
相关推荐
亓才孓2 小时前
[JDBC]事务
java·开发语言·数据库
CHU7290352 小时前
直播商城APP前端功能全景解析:打造沉浸式互动购物新体验
java·前端·小程序
侠客行03178 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪8 小时前
深入浅出LangChain4J
java·langchain·llm
老毛肚10 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
风流倜傥唐伯虎10 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
Yvonne爱编码11 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚11 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂11 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang11 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析