I have ArrayList, which containst football teams (class Team). Teams have points and i want to sort them by number of points.
public class Team {
priva
It is not actually necessary to define a custom Comparator like this.
Instead, you can easily define one, when you want to sort your ArrayList.
// Sort version.
Iteams.sort(Comparator.comparing(Team::getPoints));
// Complete version.
Iteams.sort((o1, o2) -> o1.getPoints().compareTo(o2.getPoints()));
Also there are options for second comparator, if objects are equals on the first:
// e.g. if same points, then compare their names.
Iteams.sort(Comparator.comparing(Team::getPoints).thenComparing(Team::getName));
Also note that the default sort option is ascending, but you can set it to descending using:
// e.g. Sort by points descending.
Iteams.sort(Comparator.comparing(Team::getPoints).reversed());
That way, you can sort your ArrayList in different ways whenever you want, just by adding the method you want.