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:


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:


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:


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.