Java 对集合进行排序
我正在尝试使用下面的代码对一组对象进行排序Java 对集合进行排序,java,sorting,java-8,comparator,Java,Sorting,Java 8,Comparator,我正在尝试使用下面的代码对一组对象进行排序 CompletableFuture<Set<AnnouncementDTO>> announcementsDTO = announcementRepository.findByZoneId(id) .thenApply(o -> o.stream() .sorted(new Comparator<Announcement&
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()));
CompletableFuture-announcementsDTO=announcementRepository.findByZoneId(id)
。然后应用(o->
o、 流()
.sorted(新的比较器(){
公共整数比较(左侧公告,右侧公告){
日志调试(“++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++;
log.debug(“Left Date”+Left.getCreatedDate().toLocalDateTime());
log.debug(“正确的日期”+正确的.getCreatedDate().toLocalDateTime());
日志调试(“++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++;
if(right.getCreatedDate().toLocalDateTime().isBefore(left.getCreatedDate().toLocalDateTime())){
返回-1;
}否则{
返回1;
}
}
})
.map(announcementMapper::maptodo)
.map(it->{
it.setVersion(null);
归还它;
})
.collect(Collectors.toSet());
如果不起作用,请提供任何帮助。好的,您正在对它们进行排序,然后将元素添加到一个
哈希集,该哈希集将打破排序顺序。将它们收集到LinkedHashSet
,例如Collect(Collectors.toCollection(LinkedHashSet::new))
顺便说一句,为什么不干脆Cmparator.naturalOrder()
,因为你的日期看起来已经是可比的了。或Comparator.comparating(x->x.getCreatedDate().toLocalDateTime())
您永远不会返回0
-您的Comparator未通过合同。另外,.sorted(Comparator.comparating(a->.getCreatedDate().toLocalDateTime())
也是惯用的。我强烈建议不要登录比较器
,除非您正在对一个小数据集进行排序。事实上,我对你的日志记录一点也不喜欢——它很沉重,毫无意义:它不使用参数化,因此会对生产产生巨大影响,它可以记录一次日志时记录4次,可以记录一条短消息时记录4行。可怕的。非常糟糕。此外,Collectors.toSet()
返回未排序的集。如果您想保持由或收集器生成的排序,请尝试使用列表
。toCollection(LinkedHashSet::new)
。将“set”和“ordered”放在同一句话中就像是要求冰火。哦,这是.map(it->{it.setVersion(null);返回它;})
是一种在map
方法中对底层对象进行扭曲变异的方法,它打破了各种契约。老实说-我认为在编写更多代码之前,您需要阅读更多关于Java的知识。而且比较器是无效的。“为什么不简单地comparator.naturalOrder()
”-因为它们是公告的嵌套属性<代码>比较器。比较(a->a.getCreatedDate().toLocalDateTime())
将是惯用的方法。@Boristeider是的,在电话上打字并不是回答这个问题的终极乐趣。感谢u@BoristheSpider哦,天哪,是的!:)@Eugene最糟糕的情况是,当你完成键入并发布答案后,你会立即看到有人在1-2分钟前发布了完全相同的答案:-|