【发布时间】:2017-11-19 09:26:18
【问题描述】:
我正在尝试使用以下代码对一组对象进行排序,
CompletableFuture<Set<AnnouncementDTO>> announcementsDTO = announcementRepository.findByZoneId(id)
.thenApply(o ->
o.stream()
.sorted(new Comparator<Announcement>() {
public int compare(Announcement left, Announcement right) {
log.debug("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
log.debug("Left Date" + left.getCreatedDate().toLocalDateTime());
log.debug("Right Date" + right.getCreatedDate().toLocalDateTime());
log.debug("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
if (right.getCreatedDate().toLocalDateTime().isBefore(left.getCreatedDate().toLocalDateTime())) {
return -1;
} else {
return 1;
}
}
})
.map(announcementMapper::mapToDto)
.map(it -> {
it.setVersion(null);
return it;
})
.collect(Collectors.toSet()));
如果没有任何帮助,我们将不胜感激。
【问题讨论】:
-
您永远不会返回
0- 您的比较器无法履行合同。.sorted(Comparator.comparing(a -> .getCreatedDate().toLocalDateTime()))也是惯用的。我会强烈建议不要登录Comparator,除非您正在对一个很小的数据集进行排序。事实上,我不喜欢你的日志记录——它很重而且毫无意义:它不使用参数化,所以会对生产产生巨大影响,它记录 4 次,它可以记录一次,它记录 4 行,它可以记录一条短消息.可怕。可怕到令人瞠目结舌。 -
此外,
Collectors.toSet()返回一个无序的Set。如果您想保留sorted生成的订单,请尝试List。 -
或
Collectors.toCollection(LinkedHashSet::new)。 -
将“set”和“ordered”这两个词放在同一个句子中就像要冰火一样。
-
哦,这个
.map(it -> { it.setVersion(null); return it; })是一个讽刺——在map方法中改变底层对象会破坏各种合同。老实说 - 我认为您需要在编写更多代码之前阅读更多关于 Java 的内容。
标签: java sorting java-8 comparator