Java 8 Lamba Expression examples using Comparator

Previous
Next

Java 8 has made comparator more powerful using Lambda Expression. It has introduced many new APIs for Comparator.

Let’s go through some new features of the Comparator using Lambda expression.Let’s create a very simple class called Employee:

Sort Employee list by name in classic way:

We will sort employee list in classic way

Create EmployeeMain.java

Run the above program and you will get following output:

Before Sorting:
[John : 35, Adam : 22, Arpit : 28, John : 30, Grace : 38, Arpit : 25]
After Sorting:
[Adam : 22, Arpit : 28, Arpit : 25, Grace : 38, John : 35, John : 30]

Sort Employee list by name using lambda expression:

We will sort Employee list by name using lambda expression, It will reduce complex Comparator syntax to simple line of code
Create EmployeeMain.java

Run the above program and you will get following output:

Before Sorting:
[John : 35, Adam : 22, Arpit : 28, John : 30, Grace : 38, Arpit : 25]
After Sorting:
[Adam : 22, Arpit : 28, Arpit : 25, Grace : 38, John : 35, John : 30]]

Sort Employee list by name using lambda expression without type definitions

Here we will not pass type definition to arguments in lambda expression.It will be interpreted in context
Just  change line no. 16 of Employee name from :

To

and Run EmployeeMain.java. You will get same output as above

Reverse sort:

To reverse sort the list, just change order of arguments.
Change the main method in employee main to below method:

Previous
Next

Add Comment