I have an ArrayList and want sort it in descending order. I use for it java.util.stream.Stream.sorted(Comparator)
method. Here is a description according Java API:
Returns a stream consisting of the elements of this stream, sorted according to the provided
Comparator
.
this methods return me a sort with ascending order. Which parameter should I change, just to have the descending order?
This question is related to
java
sorting
java-8
comparator
java-stream
Why not to extend the existing comperator and overwrite super and nor the result. The implementation the Comperator Interface is not nessesery but it makes it more clear what happens.
In result you get a easy reusable Class File, testable unit step and clear javadoc.
public class NorCoperator extends ExistingComperator implements Comparator<MyClass> {
@Override
public int compare(MyClass a, MyClass b) throws Exception {
return super.compare(a, b)*-1;
}
}
Java 8 Comparator
interface has a reversed
method : https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#reversed--
You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:
Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
.thenComparingInt(SomeEntity::getProperty2)
.thenComparing(SomeEntity::getProperty3, reverseOrder());
Source: Stackoverflow.com