如何按长字段对 List<Object> 进行排序

Tom*_*Tom 2 java sorting arraylist java-stream

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());
Run Code Online (Sandbox Code Playgroud)

大家好!

我的列表中有几行,并且有我想排序的时间戳。问题是比较器需要一个 int 并且我不能强制转换 long (即日期),因为如果我这样做,我会削减一些最后的数字。代码可以工作,但排序不准确(它删除了最后一位数字)。

它可能会帮助您理解:

result.stream().sorted((a,b)->a.getStartTimestamp() - b.getStartTimestamp()).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

和错误:

Type mismatch: cannot convert from long to int
Run Code Online (Sandbox Code Playgroud)

Pan*_*hal 5

利用Comparator.comparingLong()

result.stream().sorted(Comparator.comparingLong(DetailsDescription:: getStartTimestamp)).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

上面的代码可以工作。

  • @Tom这是您在问题中发布的问题的解决方案,因为 `DetailsDescription:: getStartTimestamp` 实际上返回一个 `long`。如果您没有看到预期的行为,那么问题就出在其他地方。 (3认同)