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.
ListpersonList = 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!
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Yash Arora