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

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


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.


If your stream elements implements Comparable then the solution becomes simpler:

 ...stream() .sorted(Comparator.reverseOrder())


Use

Comparator<File> comparator = Comparator.comparing(File::lastModified); Collections.sort(list, comparator.reversed());

Then

.forEach(item -> item.delete());