Lambda Expressions Comparator Example in Java 8

In this example, we will see how to use Java 8 Lambda expression to write a Comparator to sort a List of any SalesExecutive type. I am using SalesExecutive class with five attributes.  We will use this class to understand various sorting use cases.


Gender attribute in above programme is enum, so I am defining our enum class for better understanding of the code.


Example-1) Sorting based on different attribute of Sales Executive class without Lambda Expression



What we did so far in above programme.

I have written one helper method getSalesExecutiveList() which always return a list of SalesExecutive. This is just helper method. We sorted SalesExecutive objects in ascending order using their name, salary & age. If we were using comparable interface instead of Comparator in this example,  it restrict you compare these SalesExecutive objects in a single particular way only. If you want to sort this list collection, based on multiple fields, then you have to use Comparator only. Normally we use Collections.sort method and pass an anonymous Comparator class like we  did in above programme.

We don’t need to worry for Comparator, because it has been made to implement the FunctionalInterface in Java 8 as shown below.

Output of the above programme


Example-2) Sorting based on different attribute of Sales Executive class with Lambda Expression

We can implement Comparator using lambda expression because it is a SAM type interface, as It just got one abstract method compare() which means we can pass lambda expression where a Comparator is expected. You can use a lambda expression to implement Comparator and Comparable interface in Java, and not just these two but to implement any interface, which just got one abstract method. Remember Java 8 interface can have non-abstract methods as well default & static. That’s why lambda expression in Java 8 is known as SAM type, where SAM stands for Single Abstract Method.

The List interface in Java 8 now supports the sort method, no need to use Collections.sort anymore.

So we can write up our code this way also


Output of the second programme written in lambda expression.

Also check this post in which I am explaining new way of creating comparators, if you are working in java 8 using Comparator interface comparing() Method.

Leave a Reply

Your email address will not be published. Required fields are marked *