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

时间:2018-03-08 10:53:54

标签: 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());

大家好!

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

这可能有助于您理解:

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

错误:

Type mismatch: cannot convert from long to int

1 个答案:

答案 0 :(得分:3)

利用Comparator.comparingLong()

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

上面的代码可行。

相关问题