Friday, April 15, 2022

Java Lambda Expression Comparator Example

In this post we'll see how to write a Comparator as a Java lambda expression to sort a List.

Comparator as a lambda expression

Since Comparator is a functional interface, Java 8 onward Comparator can also be implemented as a lambda expression in Java.

In the example code there is a Person class with firstName, lastName and age fields. There is a list of Person objects which will be sorted on the basis of first name using a Comparator. That Comparator is implemented as a Java lambda expression.

Note that code that is commented in LambdaCompExp shows how Comparator can be implemented as an anonymous class.

Person Class

public class Person {
  private String firstName;
  private String lastName;
  private int age;
  Person(String firstName, String lastName, int age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
     
  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public int getAge() {
    return age;
  }
  
  public String toString(){
    StringBuffer sb = new StringBuffer();
    sb.append(getFirstName()).append(" ");
    sb.append(getLastName()).append(" ");
    sb.append(getAge()).append(" ");
    return sb.toString();        
  }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LambdaCompExp {

  public static void main(String[] args) {
    List<Person> personList = createList();
    
      // comparator implementation as anonymous class
      // and sorting the list element on the basis of first name
   /* Collections.sort(personList, new Comparator<Person>() {
         public int compare(Person a, Person b) {
             return a.getFirstName().compareTo(b.getFirstName());
          }
    });*/
                 
    // Providing the comparator functional interface compare
    /// method as lambda exression
    Collections.sort(personList, (Person a, Person b) -> 
        a.getFirstName().compareTo(b.getFirstName()));
     
      
    System.out.println("Sorted list with lambda implementation");
    // Using the new ForEach loop of Java 8 
    // used with lambda expression
    personList.forEach((per) -> System.out.print(per.getFirstName() + " "));

  }
    
  // Utitlity method to create list
  private static List<Person> createList(){
    List<Person> tempList = new ArrayList<Person>();
    Person person = new Person("Ram","Tiwari", 50);
    tempList.add(person);
    person = new Person("John", "Myers", 13);
    tempList.add(person);
    person = new Person("Tanuja", "Trivedi", 30);
    tempList.add(person);
    person = new Person("Amy", "Jackson", 40);
    tempList.add(person);
    System.out.println("List elements are - ");
    System.out.println(tempList);
    return tempList;
  }
}

Output

List elements are - 
[Ram Tiwari 50 , John Myers 13 , Tanuja Trivedi 30 , Amy Jackson 40 ]
Sorted list with lambda implementation
Amy John Ram Tanuja 

That's all for this topic Java Lambda Expression Comparator Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Lambda Expression Runnable Example
  2. Java Lambda Expression Callable Example
  3. Java Lambda Expression And Variable Scope
  4. Method Reference in Java
  5. Java Lambda Expressions Interview Questions And Answers

You may also like-

  1. Convert String to Byte Array Java Program
  2. Find Duplicate Elements in an Array Java Program
  3. How to Convert String to Date in Java
  4. Converting String to Enum Type in Java
  5. Interface Static Methods in Java
  6. Effectively Final in Java 8
  7. CopyOnWriteArrayList in Java With Examples
  8. Constructor Chaining in Java

No comments:

Post a Comment