java 8 lambda expression to sort a list

Posted By : Yash Arora | 22-Jul-2018

Hi all,
Today I am going to show you how you can sort a list of objects in just single line with the help of lambda expressions.

I am gonna compare the approach of sorting of objects before Java 8 lambda expressions and how things change with the newer functionality.

Suppose i have a list of persons.


List personList = new ArrayList<>();
personList.add(new Person("Virat", "Kohli"));
personList.add(new Person("Arun", "Kumar"));
personList.add(new Person("Rajesh", "Mohan"));
personList.add(new Person("Rahul", "Dravid"));

Now before lambda expression the approach of sorting should be like this


Collections.sort(personList, new Comparator(){
  public int compare(Person p1, Person p2){
    return p1.firstName.compareTo(p2.firstName);
  }
});

Now with the help of lambda expression, the code would look like


Collections.sort(personList, (Person p1, Person p2) -> p1.firstName.compareTo(p2.firstName));

Here instead of using Comparator interface and its method compare what we have done is just use lambda expression with the parameters that needs to be pass in compare() method and just write its body. Even we can remove the type information as the type information is inferred from the context in which the lambda expression is being used. So now it will look like


Collections.sort(personList, (p1, p2) -> p1.firstName.compareTo(p2.firstName));

 

Now if you remember that list also have sort functionality so we can write the single statement in such way


personList.sort((p1, p2) -> p1.firstName.compareTo(p2.firstName));

 

Hope this will be helpful!

About Author

Author Image
Yash Arora

Request for Proposal

Name is required

Comment is required

Sending message..