I'm using a Java lambda to sort a list.
How can I sort it in a reverse way?
I saw How to sort ArrayList<Long> in decreasing order?, but I want to use a 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());
-1 * answerwithanswer, the order will change to reverse of what it was with-1 * ....forEachOrderedinstead offorEachforEachOrdered, as the name suggests, cares about encounter order which is relevant as you want to skip a certain number of newest files which relies on the “sorted by modification time” order.sort→skip→(unordered)forEachshould work, is correct and that it is indeed implemented to work this way in today’s JREs, but back in 2015, when the previous comments were made, it was indeed an issue (as you may read in this question).