Java Language Creating a Comparator using comparing method


Example

Comparator.comparing(Person::getName)

This creates a comparator for the class Person that uses this person name as the comparison source. Also it is possible to use method version to compare long, int and double. For example:

Comparator.comparingInt(Person::getAge)

Reversed order

To create a comparator that imposes the reverse ordering use reversed() method:

Comparator.comparing(Person::getName).reversed()

Chain of comparators

Comparator.comparing(Person::getLastName).thenComparing(Person::getFirstName)

This will create a comparator that firs compares with last name then compares with first name. You can chain as many comparators as you want.