Monday, 9 May 2016

Lambda Expression Comparator example

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

Let's see an example, in the 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 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 Lambda Expression Comparator example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Overview of lambda expressions
  2. Functional interfaces & lambda expression
  3. Functional interface annotation in Java 8
  4. Difference between Comparable and Comparator
  5. Count total number of times each character appears in a String
  6. Lambda Expression Runnable example

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment