【发布时间】: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