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

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.


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(); = id; = 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) -> {
      for(Employee e : list) {
         System.out.println( + " " + + " " + e.salary);


Sorting the employee list based on the name
115 Adithya 25000.0
135 Chaitanya 40000.0
125 Jai 30000.0