本文介绍了如何使用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)作为黑客

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());


推荐答案

您可以调整您在将它包装在lambda中:

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以相反的顺序对流进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:22