【问题标题】:Sorting a set java对一组java进行排序
【发布时间】: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 -&gt; .getCreatedDate().toLocalDateTime())) 也是惯用的。我会强烈建议不要登录Comparator,除非您正在对一个很小的数据集进行排序。事实上,我不喜欢你的日志记录——它很重而且毫无意义:它不使用参数化,所以会对生产产生巨大影响,它记录 4 次,它可以记录一次,它记录 4 行,它可以记录一条短消息.可怕。可怕到令人瞠目结舌。
  • 此外,Collectors.toSet() 返回一个无序的Set。如果您想保留sorted 生成的订单,请尝试List
  • Collectors.toCollection(LinkedHashSet::new)
  • 将“set”和“ordered”这两个词放在同一个句子中就像要冰火一样。
  • 哦,这个.map(it -&gt; { it.setVersion(null); return it; }) 是一个讽刺——在map 方法中改变底层对象会破坏各种合同。老实说 - 我认为您需要在编写更多代码之前阅读更多关于 Java 的内容。

标签: java sorting java-8 comparator


【解决方案1】:

好吧,您正在对它们进行排序,然后将元素添加到 HashSet 中,这会破坏排序顺序。将它们收集到LinkedHashSet,而不是collect(Collectors.toCollection(LinkedHashSet::new))

顺便说一句,为什么不简单地使用Cmparator.naturalOrder(),因为您的日期看起来已经是Comparable。或Comparator.comparing(x -&gt; x.getCreatedDate().toLocalDateTime())

【讨论】:

  • 比较器也无效。
  • "为什么不简单地 Comparator.naturalOrder()" - 因为它们是 Announcement 的嵌套属性。 Comparator.comparing(a -&gt; a.getCreatedDate().toLocalDateTime()) 将是惯用的方法。
  • @BoristheSpider 对,在电话上打字并不是回答 SO 时的终极乐趣。谢谢你
  • @BoristheSpider 天哪,是的! :)
  • @Eugene 最糟糕的情况是当您完成输入然后发布答案时,您会立即看到有人在 1-2 分钟前发布了完全相同的答案:-|
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 2011-07-20
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多