How to write the comparator as a lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

A lambda expression is an anonymous method and doesn't execute on its own in java. Instead, it is used to implement a method defined by the functional interface. A lambda expression used with any functional interface and Comparator is a functional interface. The Comparator interface has used when sorting a collection of objects compared with each other.

In the below example, we can sort the employee list by name using the Comparator interface.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Employee {
   int id;
   String name;
   double salary;
   public Employee(int id, String name, double salary) {
      super();
      this.id = id;
      this.name = name;
      this.salary = salary;
   }
}
public class LambdaComparatorTest {
   public static void main(String[] args) {
      List<Employee> list = new ArrayList<Employee>();

      // Adding employees
      list.add(new Employee(115, "Adithya", 25000.00));
      list.add(new Employee(125, "Jai", 30000.00));
      list.add(new Employee(135, "Chaitanya", 40000.00));
      System.out.println("Sorting the employee list based on the name");

      // implementing lambda expression
      Collections.sort(list, (p1, p2) -> {
         return p1.name.compareTo(p2.name); 
      }); 
      for(Employee e : list) {
         System.out.println(e.id + " " + e.name + " " + e.salary);
      }
   }
}

Output

Sorting the employee list based on the name
115 Adithya 25000.0
135 Chaitanya 40000.0
125 Jai 30000.0
raja
Published on 06-Dec-2019 14:56:25
Advertisements