Why do I need a temporary variable as personAgentComparator needed here and to call reversed() on that?
public class SubTypeComparatorIssue {
public void sortAgeFromOldToYoung(List<Person> persons) {
//persons.sort(Comparator.comparing(person -> person.age).reversed());
Comparator<Person> personAgeComparator = Comparator.comparing(person -> person.age);
persons.sort(personAgeComparator.reversed());
}
}
class Person {
int age;
}
How do I get the sorting and reversing to with the comparator as a one-liner? I am getting an error in the lambda expression under person.age
when currying the reversed()
on that commented line. If the reversed() is not added, I don't get that error even! Hence did for now in two lines with that temporary personAgentComparator
and called reversed()
on it while calling the sort()
.
Basically, how do I get a oneliner to do this whole operation?
I expect a correction on this line to have it as a oneliner to get the persons
list reverse sorted by person's age.
persons.sort(Comparator.comparing(person -> person.age).reversed());
One of the way using lambda
persons.sort((p1, p2) -> Integer.compare(p2.age, p1.age));