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

    }
相关推荐
爬山算法9 分钟前
Maven(6)如何使用Maven进行项目构建?
java·maven
.生产的驴13 分钟前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
爱学的小涛21 分钟前
【NIO基础】基于 NIO 中的组件实现对文件的操作(文件编程),FileChannel 详解
java·开发语言·笔记·后端·nio
吹老师个人app编程教学21 分钟前
详解Java中的BIO、NIO、AIO
java·开发语言·nio
爱学的小涛22 分钟前
【NIO基础】NIO(非阻塞 I/O)和 IO(传统 I/O)的区别,以及 NIO 的三大组件详解
java·开发语言·笔记·后端·nio
北极无雪26 分钟前
Spring源码学习:SpringMVC(4)DispatcherServlet请求入口分析
java·开发语言·后端·学习·spring
琴智冰30 分钟前
SpringBoot
java·数据库·spring boot
binqian30 分钟前
【SpringSecurity】基本流程
java·spring
猿小蔡-Cool1 小时前
CPU 多级缓存
java·spring·缓存
gopher95111 小时前
final,finally,finalize的区别
java·开发语言·jvm