Implementing the Comparator Interface

The Comparator interface is used in hundreds of places in the JDK library, from searching operations to sorting, reversing, and so on. In Java 8 this has turned into a functional interface; the benefit is that we can use charmingly fluent syntax to implement comparators.

Let’s create a few different implementations of the Comparator to understand the influence of the new style. Our fingers will thank us for all the keystrokes saved by not having to create anonymous inner classes.

Sorting with a Comparator

We’ll build an example to sort a list of people using a few different points of comparisons. Let’s first create the Person JavaBean.

compare/fpij/Person.java
 
public​ ​class​ Person {
 
private​ ​final ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.