Comparison and Sorting with Lambda

Comparison and Sorting with Lambda


In Java 8 lambda expressions were added to make Java code more concise and readable.

Lambda expressions are similar to methods. However, unlike other methods, lambda expressions do not need a name. You can implement a lambda expression right in the body of a method.

If you are new to lambda expressions I suggest you go through my basic post on the same-titled What’s all the fuss about Java Lambdas?

In this post, I am going to explain how you can use lambda expressions to compare and sort Java objects stored in collections.


I am using a Product class with four attributes. We will compare and sort objects of this Product class.

The code of the Product class is this.

public class Product {
   int id;
   String name;
   String description;
   float price;

   public int getId() {
        return id;

   public void setId(int id) { = id;

   public String getName() {
        return name;

   public void setName(String name) { = name;

   public float getPrice() {
       return price;

   public void setPrice(float price) {
       this.price = price;

   public String getDescription() {
       return description;

   public void setDescription(String description) {
       this.description = description;

   public Product(int id, String name, String description, float price) { = id; = name;
       this.description = description;
       this.price = price;

   public String toString() {
       return "\n["","", "+this.description+", "+this.price+"]";

Next, I have initialized a list of products in thein the main class named like this.

The code is this.

List<Product> productList = new ArrayList<Product>();

productList.add(new Product(26,"ball","redball",100));
productList.add(new Product(6,"table","browntable",3800));
productList.add(new Product(234,"chair","plasticchair",1500));
productList.add(new Product(65,"table","steeltable",70));
productList.add(new Product(15,"bedsheet","cotton",1250));

System.out.println("Before Sorting the product data:");


On running the program, the unsorted product list is this.

output before sorting

Comparison with Lambda

You can compare and sort Product objects based on various properties both with and without lambda expressions. However, when you use lambda expressions it makes your code concise and easier to read.

Java 8 supports the  List.sort method directly, so no need to use the legacy Collections.sort   method anymore.

The following is the code for sorting the product list by their price using lambda expressions.

//lambda expression for sorting product by price in ascending order
System.out.println("After sorting the product data by price in ascending order");
productList.sort((Product product1, Product product2)-> (int)(product1.getPrice()-product2.getPrice()));

The output is this.

without comparator

Using Comparator to Compare and Sort by Name

Another way to compare and sort the product list is by using the comparing method of Comparator in a lambda expression.

The following code shows this.

//Sort all products by their name
System.out.println("After sorting the product data by name");
productList.sort(Comparator.comparing(product1 -> product1.getName()));
productList.forEach((product -> System.out.println(product)));

The code produces this output.

sort by name

Reverse Sort

You can also do reverse sort with lambda expressions in the sort method of the List interface.

The code to sort the list of Product objects by their name in reverse order is this.

System.out.println("In reverse order");
Comparator<Product> comparator = Comparator.comparing(e -> e.getName());

The output is this.

sorting in reverse order

Sorting on Multiple fields

Sorting can also be done in multiple fields by using Comparators.

In the following code, sorting is done on the product list by the product name first and then again based on their description.

System.out.println("Sorting by name first and then description“);


This is the output.

sorting for multiple fields

Parallel Sort

If a collection has thousands of objects, then you should opt for a parallel sort. This is because the parallel sort is really fast in comparison to the regular sort.

This is the code to implement parallel sort using lambda expressions.

Product[] productsArray = productList.toArray(new Product[productList.size()]);

Comparator<Product> groupByComparator = Comparator.comparing(Product::getName)

//Parallel sorting
Arrays.parallelSort(productsArray, groupByComparator);


Sorting With Stream.sorted()

You can sort a collection using Java 8’s Stream sorted() API as well.

This is the code to use a custom Comparator with a sorted() API:

Comparator<Product> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());

List<Product> sortedProduct =;

Here, I have sorted the product list based on name using a custom Comparator named nameComparator with the Stream Sorted () API.

You can simplify the above code even further by using  Comparator.comparing() method:

This is the code.

List<Product> sortedProductList =

The above code produces the following output.

steam sort

Reverse Sorting with Stream. sorted()

Similarly, reverse sort can be implemented as well by adding the Comparator.reverseOrder() method.

System.out.println("Reverse order sorting using Stream sorted API");

List<Product> reverseSortedProduct =
        .sorted(Comparator.comparing(Product::getName, Comparator.reverseOrder()))


This is the output.

reverse in stream sorted

You can find the source code of this post on Github.

About SFG Contributor

Staff writer account for Spring Framework Guru

    You May Also Like

    Leave a Reply

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

    This site uses Akismet to reduce spam. Learn how your comment data is processed.