Comparison and Sorting with Lambda
0 CommentsLast Updated on January 5, 2021 by jt
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.
Overview
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.
Product.java
public class Product { int id; String name; String description; float price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.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) { this.id = id; this.name = name; this.description = description; this.price = price; } @Override public String toString() { return "\n["+this.id+","+this.name+", "+this.description+", "+this.price+"]"; } }
Next, I have initialized a list of products in thein the main class named Main.java 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:"); productList.forEach((product)->System.out.println(product));
On running the program, the unsorted product list is this.
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())); System.out.println(productList);
The output is this.
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.
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()); productList.sort(comparator.reversed()); System.out.println(productList);
The output is this.
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.
//multiple System.out.println("Sorting by name first and then description“); productList.sort(Comparator.comparing(Product::getName).thenComparing(Product::getDescription)); System.out.println(productList);
This is the output.
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) .thenComparing(Product::getDescription); //Parallel sorting Arrays.parallelSort(productsArray, groupByComparator); System.out.println(productsArray);
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 = productList.stream().sorted(nameComparator).collect(Collectors.toList()); System.out.println(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 = productList.stream() .sorted(Comparator.comparing(Product::getName)) .collect(Collectors.toList()); System.out.println(sortedProductList);
The above code produces the following output.
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 = productList.stream() .sorted(Comparator.comparing(Product::getName, Comparator.reverseOrder())) .collect(Collectors.toList()); System.out.println(reverseSortedProduct);
This is the output.
You can find the source code of this post on Github.