Sunday, June 28, 2015

Java 8: Composing Comparators

In my last post, I showed how you can sort a list of Person objects by age, using the following statement:

list.sort(comparingInt(Person::getAge));

What if you want to sort the objects in order of decreasing age instead? There's no need to create a new instance of Comparator, because the Comparator interface has a handy default method reversed that reverses its ordering:

list.sort(comparingInt(Person::getAge).reversed());

Now, what if you want to sort people by name if they have the same age. The thenComparing method allows you to do just that, as shown below:

list.sort(comparingInt(Person::getAge)
    .reversed()
    .thenComparing(Person::getName));

No comments:

Post a Comment