I have a List of doubles in java and I want to sort ArrayList in descending order.
Input ArrayList is as below:
List testList = new Arr
Using lambdas (Java8), and stripping it down to the barest of syntax (the JVM will infer plenty in this case), you get:
Collections.sort(testList, (a, b) -> b.compareTo(a));
A more verbose version:
// Implement a reverse-order Comparator by lambda function
Comparator comp = (Double a, Double b) -> {
return b.compareTo(a);
};
Collections.sort(testList, comp);
The use of a lambda is possible because the Comparator interface has only a single method to implement, so the VM can infer which method is implementing. Since the types of the params can be inferred, they don't need to be stated (i.e. (a, b)
instead of (Double a, Double b)
. And since the lambda body has only a single line, and the method is expected to return a value, the return
is inferred and the braces aren't necessary.