如何使用 Java8 lambda 以相反的顺序对流进行排序? [英] How to use a Java8 lambda to sort a stream in reverse order?
本文介绍了如何使用 Java8 lambda 以相反的顺序对流进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 java lambda 对列表进行排序.
I'm using java lambda to sort a list.
我怎样才能以相反的方式对其进行排序?
how can I sort it in a reverse way?
我看到了这个帖子,但我想使用 java 8 lambda.
I saw this post, but I want to use java 8 lambda.
这是我的代码(我使用 * -1)作为 hack
Here is my code (I used * -1) as a hack
Arrays.asList(files).stream()
.filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
.sorted(new Comparator<File>() {
public int compare(File o1, File o2) {
int answer;
if (o1.lastModified() == o2.lastModified()) {
answer = 0;
} else if (o1.lastModified() > o2.lastModified()) {
answer = 1;
} else {
answer = -1;
}
return -1 * answer;
}
})
.skip(numOfNewestToLeave)
.forEach(item -> item.delete());
推荐答案
您可以调整您在 如何对ArrayList
You can adapt the solution you linked in How to sort ArrayList<Long> in Java in decreasing order? by wrapping it in a lambda:
.sorted((f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified())
注意f2是Long.compare
的第一个参数,不是第二个,所以结果会颠倒.
note that f2 is the first argument of Long.compare
, not the second, so the result will be reversed.
这篇关于如何使用 Java8 lambda 以相反的顺序对流进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文