java stream 取list时间较大的元素list

package com.qianfan123.sail.cre.sync.dmp.plugin.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // 创建包含对象的列表
        List<MyObject> list = new ArrayList<>();
        list.add(new MyObject("code1", new Date(1631362800000L))); // 2021-09-11
        list.add(new MyObject("code2", new Date(1631449200000L))); // 2021-09-12
        list.add(new MyObject("code1", new Date(1631535600000L))); // 2021-09-13
        list.add(new MyObject("code3", new Date(1631622000000L))); // 2021-09-14

        // 使用流操作和Collectors.groupingBy获取每个code对应的最新对象
        Map<String, List<MyObject>> latestObjectsMap = list.stream()
                .collect(Collectors.groupingBy(MyObject::getCode,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparing(MyObject::getUpdateDate)),
                                obj -> obj.map(Arrays::asList).orElse(new ArrayList<>()))));

        // 提取映射中的值列表并合并为一个列表
        List<MyObject> latestObjectsList = latestObjectsMap.values().stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());

        // 输出最新的对象列表
        System.out.println("Latest objects: " + latestObjectsList);
    }

    // 自定义的对象类
    static class MyObject {
        private String code;
        private Date updateDate;

        public MyObject(String code, Date updateDate) {
            this.code = code;
            this.updateDate = updateDate;
        }

        public String getCode() {
            return code;
        }

        public Date getUpdateDate() {
            return updateDate;
        }

        @Override
        public String toString() {
            return "MyObject{" +
                    "code='" + code + '\'' +
                    ", updateDate=" + updateDate +
                    '}';
        }
    }
}
posted @ 2023-09-12 14:01  BigOrang  阅读(239)  评论(0编辑  收藏  举报