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.

Example

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
      emp.stream().sorted(Comparator.comparing(Employee::getFirstName)
         .thenComparing(Employee::getLastName))
         .forEach(System.out::println);
   }
}

// Employee class
class Employee {
   int age;
   String firstName;
   String lastName;
   public Employee(int age, String firstName, String lastName) {
      super();
      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;
   }
   @Override
   public String toString() {
      return "Employee [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + "]";
   }
}

Output

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]
raja
Published on 07-Jan-2020 12:37:20
Advertisements