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...!!! Click To Tweet

 

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...!!! Click To Tweet

 

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

Other Useful References: