Java 8 比较器不工作

Java 8 comparator not working

我有一个基本的 Spring 启动应用程序。使用 Spring 初始化程序、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR 文件 我有这段代码来比较 POJO,但是比较器似乎不起作用,因为 lastDeviceEvent 和 firstDeviceEvent 是具有相同 ID

的同一个对象
DeviceEvent lastDeviceEvent = null;
        DeviceEvent firstDeviceEvent = null;

        try {       

            lastDeviceEvent = deviceEvents
                            .stream()
                            .filter (o -> o.getId().equals(deviceId))
                            .sorted(comparing((DeviceEvent de) -> de.getId()).reversed())
                            .findFirst().get();



            firstDeviceEvent = deviceEvents
                    .stream()
                    .filter (o -> o.getId().equals(deviceId)) 
                    .sorted(comparing((DeviceEvent de) -> de.getId()))
                    .findFirst().get();


            LOG.info("lastDeviceEvent --> " + lastDeviceEvent.getId());
            LOG.info("firstDeviceEvent -> " + firstDeviceEvent.getId());


        } catch (NoSuchElementException nse) {

            throw new AccessDeniedException("403 Forbidden");

        }

比较器似乎是正确的。问题似乎出在您的过滤器子句中,您将 事件 ID 设备 ID

进行比较
lastDeviceEvent = deviceEvents
                .stream()
                .filter (o -> o.getDeviceId().equals(deviceId)) // Original code used getId()
                .sorted(comparing((DeviceEvent de) -> de.getId()).reversed())
                .findFirst()
                .get();