In this post, we will show you two different approaches to perform a collection sorting. One way is through traditional way by using Comparator class and in next example, we will see how to use Lambda expression that came into existence since Java 8 to sort the collections and making the code much elegant and declarative. In this example, we will see How to replace a classic Comparator to sort a collection with Java 8 Lambda expression?”.

Easiest representation of collections sorting using Java 8 Lambda...!!! Share on X

 

In this tutorial, we are going to cover below topics:

  • Collection sorting with classic Comparator (solution before Java 8)
  • Collection sorting using lambda expression (solution after Java 8)

 

Let’s begin:

1. Collection sorting using Comparator (without Lambda)

Comparator Syntax:

 

Example:

In this example, we are sorting the list by age using classic comparator.

 

Output:

 

2. Collections sorting using Lambda

Lambda syntax:

Sort the list directly using Lambda expression in Java 8. There is no need to pass the list into collections object before comparing it anymore. 

 

Example:

In this example, we are sorting the list by age using Java 8 Lambda expression.

 

Output:

 

See, how elegant and powerful Java 8 Lambda is.

Easiest representation of collections sort using Java 8 Lambda...!!! Share on X

 

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak