【问题标题】:How to sort List<Object> by long field如何按长字段对 List<Object> 进行排序
【发布时间】:2018-03-08 10:53:54
【问题描述】:
List<DetailsDescription> result = new ArrayList<>();
result.add(
     new DetailsDescription(((Date) row.getObject("alarm_start_timestamp")).getTime()));

result.stream().sorted(Comparator.comparing(DetailsDescription::getStartTimestamp)
               .reversed())
               .limit(PAGE_SIZE)
               .collect(Collectors.toList());

大家好!

我的列表中有几行,并且有我想要排序的时间戳。问题是 Comparator 需要一个 int 并且我不能投长(这是日期),因为如果我这样做,我会削减一些最后的数字。代码有效,但排序不准确(它会删除最后一位)。

它可能会帮助你理解:

result.stream().sorted((a,b)->a.getStartTimestamp() - b.getStartTimestamp()).collect(Collectors.toList());

还有错误:

Type mismatch: cannot convert from long to int

【问题讨论】:

  • Comparator.comparing(DetailsDescription::getStartTimestamp)排序有什么问题?
  • 日期已经实现 Comparable
  • @daniu 我使用 noSQL 数据库,我不能在那里按日期排序,所以我想在这里用 java 来做。日期实际上很长。
  • @user7 你能解释一下吗?

标签: java sorting arraylist java-stream


【解决方案1】:

利用Comparator.comparingLong():

result.stream().sorted(Comparator.comparingLong(DetailsDescription:: getStartTimestamp)).collect(Collectors.toList());

上面的代码可以工作。

【讨论】:

  • 还是不行。在某些记录中,它没有排序,并且时间戳不会减少。我不确定 Cassandra 是否会制造一些麻烦。
  • @Tom 这是您在问题中发布的问题的解决方案,因为DetailsDescription:: getStartTimestamp 实际上返回了long。如果您没有看到预期的行为,那么问题出在其他地方。
猜你喜欢
  • 2022-08-19
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 2010-09-10
  • 2021-05-11
  • 2010-10-17
相关资源
最近更新 更多