I want to sort a List of objects by a specified attribute of those objects and I want to choose which attribute should be used for sorting. Example:
class
I would say the easiest way to do this is to create a comparator:
final Comparator byName = Comparator.comparing(Car::name);
final Comparator byColour = Comparator.comparing(Car::colour);
Then just use the appropriate method on Arrays to sort by a comparator:
Arrays.sort(carArray, byName);
Now you want to do it with an enum? Just have the enum implements Comparator:
enum SortBy implements Comparator {
NAME(Comparator.comparing(Car::name)),
COLOUR(Comparator.comparing(Car::colour));
private final Comparator delegate;
private SortBy(Comparator delegate) {
this.delegate = delegate;
}
@Override
public int compare(final Car o1, final Car o2) {
return delegate.compare(o1, o2);
}
}
Want to sort by name then by colour? Easy:
final Comparator byName = SortBy.NAME.thenComparing(SortBy.COLOUR);
Want to sort by name in reverse order? Easy:
final Comparator byName = SortBy.NAME.reversed();