Java Reference
In-Depth Information
The comparing() method takes a Function and returns a Comparator . The Function should return a Comparable
that is used to compare two objects. You can create a Comparator object to compare Person objects based on their first
name, as shown:
Comparator<Person> firstNameComp = Comparator.comparing(Person::getFirstName);
The thenComparing() method is a default method. It is used to specify a secondary comparison if two objects are
the same in sorting order based on the primary comparison. The following statement creates a Comparator<Person>
that sorts Person objects based on their last names, first names, and DOBs:
Comparator<Person> lastFirstDobComp =
Comparator.comparing(Person::getLastName)
.thenComparing(Person::getFirstName)
.thenComparing(Person::getDob);
The program in Listing 5-23 shows how to use the method references to create a Comparator objects to sort
Person objects. It uses the sort() default method of the List interface to sort the list of persons. The sort() method
takes a Comparator as an argument. Thanks to lambda expressions and default methods in interfaces for making the
sorting task so easy!
Listing 5-23. Sorting a List of Person Objects
// ComparingObjects.java
package com.jdojo.lambda;
import java.util.Comparator;
import java.util.List;
public class ComparingObjects {
public static void main(String[] args) {
List<Person> persons = Person.getPersons();
// Sort using the first name
persons.sort(Comparator.comparing(Person::getFirstName));
// Print the sorted list
System.out.println("Sorted by the first name:");
FunctionUtil.forEach(persons, System.out::println);
// Sort using the last name, first name, and then DOB
persons.sort(Comparator.comparing(Person::getLastName)
.thenComparing(Person::getFirstName)
.thenComparing(Person::getDob));
// Print the sorted list
System.out.println("\nSorted by the last name, first name, and dob:");
FunctionUtil.forEach(persons, System.out::println);
}
}
 
Search WWH ::




Custom Search