Java 8 – Sort a List Using Lambda Expression

Introduction

Java 8 introduced lambda expressions, which provide a concise and functional way to express behavior as an anonymous method. One of the common use cases for lambda expressions is sorting a list. Prior to Java 8, sorting a list involved creating an anonymous Comparator class, but with lambda expressions, this process is simplified and more readable. Java 8’s List interface includes the sort() method, which can be used in combination with a lambda expression to achieve sorting in a streamlined way.

In this guide, we’ll explore how to sort a list of elements using lambda expressions in Java 8.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Sorting a List of Strings
    • Sorting a List of Custom Objects
  • Advanced Considerations
  • Conclusion

Problem Statement

The task is to create a Java program that:

  • Sorts a list of strings using a lambda expression.
  • Sorts a list of custom objects (e.g., a list of Person objects) using a lambda expression.

Example:

  • Input: A list of strings ["Banana", "Apple", "Cherry"].
  • Output: A sorted list of strings ["Apple", "Banana", "Cherry"].

Solution Steps

  1. Create a List: Define a list of elements that you want to sort.
  2. Use the sort() Method: Utilize the List.sort() method with a lambda expression to define the sorting logic.
  3. Display the Sorted List: Print or otherwise use the sorted list.

Java Program

Sorting a List of Strings

The following example demonstrates how to sort a list of strings using a lambda expression.

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

public class SortListLambdaExample {

    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
        fruits.sort((s1, s2) -> s1.compareTo(s2));

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

Output

Sorted list: [Apple, Banana, Cherry]

Sorting a List of Custom Objects

The following example demonstrates how to sort a list of custom objects using a lambda expression. Let’s assume you have a Person class with name and age attributes.

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

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

public class SortCustomObjectListLambda {

    public static void main(String[] args) {
        // Step 1: Create a List of Person objects
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // Step 2: Sort the List by age using a lambda expression
        people.sort((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()));

        // Step 3: Display the sorted list
        System.out.println("Sorted list by age: " + people);

        // Step 4: Sort the List by name using a lambda expression
        people.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));

        // Step 5: Display the sorted list by name
        System.out.println("Sorted list by name: " + people);
    }
}

Output

Sorted list by age: [Bob (25), Alice (30), Charlie (35)]
Sorted list by name: [Alice (30), Bob (25), Charlie (35)]

Explanation

  • Sorting Strings: fruits.sort((s1, s2) -> s1.compareTo(s2)); sorts the list of strings in natural (alphabetical) order using a lambda expression. The compareTo() method is used to compare two strings lexicographically.
  • Sorting Custom Objects by Age: people.sort((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge())); sorts the list of Person objects by age. The lambda expression compares the ages of two Person objects.
  • Sorting Custom Objects by Name: people.sort((p1, p2) -> p1.getName().compareTo(p2.getName())); sorts the list of Person objects by name using the compareTo() method on the name field.

Advanced Considerations

  • Reversed Order: If you want to sort the list in reverse order, you can use Comparator.reverseOrder() or chain .reversed() to the lambda expression.

  • Multiple Criteria: You can sort by multiple criteria using Comparator chaining, e.g., Comparator.comparing(Person::getName).thenComparing(Person::getAge).

  • Null Handling: Ensure to handle nulls if your list may contain null values, using Comparator.nullsFirst() or Comparator.nullsLast().

Conclusion

This guide demonstrates how to sort a list using lambda expressions in Java 8. Whether sorting simple lists of strings or more complex lists of custom objects, lambda expressions provide a concise and readable way to define the sorting logic. By leveraging the power of the List.sort() method and lambda expressions, you can perform sorting operations in a clean and efficient manner, making your code easier to maintain and understand.

Leave a Comment

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

Scroll to Top