Java Comparator thenComparing() Example

Java 8 example of sorting a collection of objects on multiple fields (ORDER BY sort) using Comparator thenComparing() method.

Java 10

Java example of sorting a List of objects by multiple fields using Comparator.thenComparing() method. This method returns a lexicographic-order Comparator with another specified Comparator. This method gives the same effect as SQL ORDER BY clause.

//first name comparator
Comparator<Employee> compareByFirstName = Comparator.comparing( Employee::getFirstName );
 
//last name comparator
Comparator<Employee> compareByLastName = Comparator.comparing( Employee::getLastName );
 
//Compare by first name and then last name (multiple fields)
Comparator<Employee> compareByFullName = compareByFirstName.thenComparing(compareByLastName);
 
//Use Comparator
Collections.sort(employees, compareByFullName);

Sorting on Multiple Fields – ORDER BY Sort

Example of using thenComparing() to create Comparator which is capable of sorting by multiple fields.

private static ArrayList<Employee> getUnsortedEmployeeList() 
{
	ArrayList<Employee> list = new ArrayList<>();
	list.add( new Employee(2, "Lokesh", "Gupta") );
	list.add( new Employee(1, "Alex", "Gussin") );
	list.add( new Employee(4, "Brian", "Sux") );
	list.add( new Employee(5, "Neon", "Piper") );
	list.add( new Employee(3, "David", "Beckham") );
	list.add( new Employee(7, "Alex", "Beckham") );
	list.add( new Employee(6, "Brian", "Suxena") );
  return list;
}


ArrayList<Employee> employees = getUnsortedEmployeeList();
 
//Compare by first name and then last name
Comparator<Employee> compareByName = Comparator
                    .comparing(Employee::getFirstName)
                    .thenComparing(Employee::getLastName);
 
Collections.sort(employees, compareByName);

Checkout the program output that has the employees sorted first by firstName, and then by lastName in dictionary order.

[E[id=7, firstName=Alex,  lastName=Beckham], 
E [id=1, firstName=Alex,  lastName=Gussin], 
E [id=4, firstName=Brian,   lastName=Sux], 
E [id=6, firstName=Brian,   lastName=Suxena], 
E [id=3, firstName=David,   lastName=Beckham], 
E [id=2, firstName=Lokesh,  lastName=Gupta], 
E [id=5, firstName=Neon,  lastName=Piper]]

Drop me your questions in the comments section.

Happy Learning !!

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
11 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.