How to use a Java8 lambda to sort a stream in reverse order?

Elad Benda2 picture Elad Benda2 · Feb 19, 2015 · Viewed 295.6k times · Source

I'm using java lambda to sort a list.

how can I sort it in a reverse way?

I saw this post, but I want to use java 8 lambda.

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

Answer

Adrian Leonhard picture Adrian Leonhard · Feb 19, 2015

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

note that f2 is the first argument of Long.compare, not the second, so the result will be reversed.