How to sort a list using Comparator with method reference in Java 8?

Java 8Object Oriented ProgrammingProgramming

Java 8 introduced changes in the Comparator interface that allows us to compare two objects. These changes help us to create comparators more easily. The first important method added is the comparing() method. This method receives as a parameter Function that determines the value to be compared and creates Comparator. Another important method is the thenComparing() method. This method can be used to compose Comparator.

In the below example, we can sort a list by using the first name with comparing() method and then the last name with the thenComparing() method of Comparator interface.


import java.util.*;

public class MethodReferenceSortTest {
   public static void main(String[] args) {
      List<Employee> emp = new ArrayList<Employee>();
      emp.add(new Employee(25, "Raja", "Ramesh"));
      emp.add(new Employee(30, "Sai", "Adithya"));
      emp.add(new Employee(28, "Jai", "Dev"));
      emp.add(new Employee(23, "Ravi", "Chandra"));
      emp.add(new Employee(35, "Chaitanya", "Krishna"));
      // using method reference

// Employee class
class Employee {
   int age;
   String firstName;
   String lastName;
   public Employee(int age, String firstName, String lastName) {
      this.age = age;
      this.firstName = firstName;
      this.lastName = lastName;
   public int getAge() {
      return age;
   public void setAge(int age) {
      this.age = age;
   public String getFirstName() {
      return firstName;
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   public String getLastName() {
      return lastName;
   public void setLastName(String lastName) {
      this.lastName = lastName;
   public String toString() {
      return "Employee [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + "]";


Employee [age=35, firstName=Chaitanya, lastName=Krishna]
Employee [age=28, firstName=Jai, lastName=Dev]
Employee [age=25, firstName=Raja, lastName=Ramesh]
Employee [age=23, firstName=Ravi, lastName=Chandra]
Employee [age=30, firstName=Sai, lastName=Adithya]
Published on 07-Jan-2020 12:37:20