Since Comparator is a SAM interface you can write this code more concise using a lambda:
Collections.sort(arrayList, {x : Int, y: Int -> y - x})
Or even
Collections.sort(arrayList) {
x, y -> y - x
}
since the lambda is the last parameter of the sort
function and the datatype of x
and y
can be inferred.
Taking two objects and having to define a single integer for them is an abstraction of a sort definition. You basically specify in which order those elements would be layed out if sorted.
For sorting integers it might seem like an overkill, but consider having to sort more complex objects for example instances of a class Car
.
This class has a colorCode
and you want to sort by that:
Collections.sort(cars) {
car1, car2 -> car1.colorCode - car2.colorCode
}
That is how you would define an order for those objects in an abstract way.