【问题标题】:Java 8 comparator not workingJava 8 比较器不工作
【发布时间】:2018-06-16 10:47:20
【问题描述】:

我有一个基本的 SpringBoot 应用程序。使用 Spring Initializer、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 升序排序会做什么?还是降序排序?如果你猜它会做什么什么都不做,那么你猜对了,因为 Java 排序是稳定的相等的元素不会被重新排序作为排序的结果。重新考虑您要完成的工作。

标签: java list lambda java-stream comparator


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 2015-11-02
    • 2018-08-10
    • 1970-01-01
    • 2015-10-11
    • 2014-06-13
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多