Java 8 – Implement Comparator Using Lambda

Introduction

Java 8 introduced lambda expressions, which provide a concise and functional way to express behavior in Java. One of the most common use cases for lambda expressions is implementing the Comparator interface. The Comparator interface is used to define custom sorting logic for objects, and before Java 8, this typically involved creating anonymous inner classes. With lambda expressions, you can implement Comparator in a more readable and concise way.

In this guide, we’ll explore how to implement the Comparator interface using lambda expressions in Java 8. We’ll cover sorting simple data types and custom objects.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Implementing Comparator for Simple Data Types
    • Implementing Comparator for Custom Objects
  • Advanced Considerations
  • Conclusion

Problem Statement

The task is to create a Java program that:

  • Implements the Comparator interface using lambda expressions.
  • Sorts a list of simple data types (e.g., String, Integer) and custom objects (e.g., Product).

Example:

  1. Simple Example: Sort a list of strings alphabetically.
  2. Custom Objects Example: Sort a list of Product objects by price.

Solution Steps

  1. Create a Simple List: Define a list of simple data types like String or Integer.
  2. Create a List of Custom Objects: Define a list of custom objects (e.g., Product).
  3. Use Lambda Expressions: Implement the Comparator interface using lambda expressions for sorting.
  4. Sort the List: Use Collections.sort() or List.sort() to sort the list.

Java Program

Implementing Comparator for Simple Data Types

Let’s start with a simple example where we sort a list of strings alphabetically.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorLambdaExample {

    public static void main(String[] args) {
        // Step 1: Create a List of Strings
        List<String> fruits = new ArrayList<>();
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Cherry");

        // Step 2: Sort the list using a lambda expression
        Collections.sort(fruits, (s1, s2) -> s1.compareTo(s2));

        // Step 3: Display the sorted list
        System.out.println("Sorted list: " + fruits);
    }
}

Output

Sorted list: [Apple, Banana, Cherry]

Explanation

  • Lambda Expression: (s1, s2) -> s1.compareTo(s2) implements the Comparator interface’s compare() method, which sorts the strings in natural (alphabetical) order.
  • Sorting: The Collections.sort() method sorts the list using the provided comparator.

Implementing Comparator for Custom Objects

Now, let’s consider a more complex example where we sort a list of custom Product objects by price.

import java.util.ArrayList;
import java.util.List;

class Product {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return name + " ($" + price + ")";
    }
}

public class ComparatorLambdaCustomObjects {

    public static void main(String[] args) {
        // Step 1: Create a List of Product objects
        List<Product> products = new ArrayList<>();
        products.add(new Product("Laptop", 1200.00));
        products.add(new Product("Smartphone", 800.00));
        products.add(new Product("Tablet", 300.00));

        // Step 2: Sort the list by price using a lambda expression
        products.sort((p1, p2) -> Double.compare(p1.getPrice(), p2.getPrice()));

        // Step 3: Display the sorted list
        System.out.println("Sorted list by price: " + products);
    }
}

Output

Sorted list by price: [Tablet ($300.0), Smartphone ($800.0), Laptop ($1200.0)]

Explanation

  • Product Class: The Product class represents a product with a name and price.
  • Lambda Expression: (p1, p2) -> Double.compare(p1.getPrice(), p2.getPrice()) implements the Comparator interface’s compare() method to sort the products by price in ascending order.
  • Sorting: The List.sort() method sorts the list using the provided comparator.

Advanced Considerations

  • Reversed Order: If you need to sort in descending order, you can reverse the comparison or use .reversed() on the comparator.

    products.sort((p1, p2) -> Double.compare(p2.getPrice(), p1.getPrice()));
    // or
    products.sort(Comparator.comparingDouble(Product::getPrice).reversed());
    
  • Multiple Criteria: You can chain comparators to sort by multiple criteria.

    products.sort(Comparator.comparing(Product::getName).thenComparing(Product::getPrice));
    
  • Null Handling: Ensure to handle potential null values in your list or map, especially when dealing with custom objects.

Conclusion

This guide demonstrates how to implement the Comparator interface using lambda expressions in Java 8. Whether sorting simple types like strings or more complex custom objects like Product, lambda expressions provide a clean and efficient way to define sorting logic. By leveraging the power of lambda expressions, you can simplify your code and make it more readable while still achieving the desired sorting functionality.

Leave a Comment

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

Scroll to Top