Java 8 Lambda for Sorting a List of Objects

Introduction

Sorting a list of objects is a common requirement in many applications. Java 8 introduced lambda expressions, which make it easy to sort a list of objects by their attributes, such as employee name, salary, or age.

Problem Statement

Write a Java program that:

  • Defines a list of Employee objects.
  • Sorts the list based on attributes like name and salary.
  • Displays the sorted list.

Example:

  • Input: A list of Employee objects.
  • Output: A list sorted by name or salary.

Step-by-Step Implementation

Step 1: Define the Employee Class

class Employee {
    private String name;
    private int salary;

    public Employee(String name, int salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public int getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return name + " (Salary: " + salary + ")";
    }
}
  • The Employee class has two attributes: name and salary.
  • The toString() method is overridden to display employee details in a readable format.

Step 2: Create a List of Employee Objects

import java.util.Arrays;
import java.util.List;

public class EmployeeSortingExample {
    public static void main(String[] args) {
        // Create a list of Employee objects
        List<Employee> employees = Arrays.asList(
            new Employee("Rahul", 55000),
            new Employee("Anjali", 60000),
            new Employee("Rajesh", 45000),
            new Employee("Priya", 70000)
        );

        // Step 3: Sort the list by salary
        employees.sort((e1, e2) -> Integer.compare(e1.getSalary(), e2.getSalary()));

        // Step 4: Display the sorted list
        System.out.println("Employees sorted by salary:");
        employees.forEach(System.out::println);
    }
}

Output

Employees sorted by salary:
Rajesh (Salary: 45000)
Rahul (Salary: 55000)
Anjali (Salary: 60000)
Priya (Salary: 70000)

Explanation

  • employees.sort((e1, e2) -> Integer.compare(e1.getSalary(), e2.getSalary())): This lambda expression compares two employees based on their salary and sorts them in ascending order.
  • employees.forEach(System.out::println): This method prints each employee using the overridden toString() method.

Sorting by Name (Alphabetically)

You can also sort the employees by name in alphabetical order.

Example

import java.util.Arrays;
import java.util.List;

public class EmployeeSortingByNameExample {
    public static void main(String[] args) {
        // Create a list of Employee objects
        List<Employee> employees = Arrays.asList(
            new Employee("Rahul", 55000),
            new Employee("Anjali", 60000),
            new Employee("Rajesh", 45000),
            new Employee("Priya", 70000)
        );

        // Sort the list by name (alphabetically)
        employees.sort((e1, e2) -> e1.getName().compareTo(e2.getName()));

        // Display the sorted list
        System.out.println("Employees sorted by name:");
        employees.forEach(System.out::println);
    }
}

Output

Employees sorted by name:
Anjali (Salary: 60000)
Priya (Salary: 70000)
Rahul (Salary: 55000)
Rajesh (Salary: 45000)

Explanation

  • employees.sort((e1, e2) -> e1.getName().compareTo(e2.getName())): This lambda expression compares two employees based on their names in lexicographical order.
  • The result is a list sorted alphabetically by employee names.

Sorting in Descending Order

You can reverse the comparison in the lambda expression to sort the list in descending order.

Example: Sort by Salary in Descending Order

import java.util.Arrays;
import java.util.List;

public class EmployeeSortingDescending {
    public static void main(String[] args) {
        // Create a list of Employee objects
        List<Employee> employees = Arrays.asList(
            new Employee("Rahul", 55000),
            new Employee("Anjali", 60000),
            new Employee("Rajesh", 45000),
            new Employee("Priya", 70000)
        );

        // Sort the list by salary in descending order
        employees.sort((e1, e2) -> Integer.compare(e2.getSalary(), e1.getSalary()));

        // Display the sorted list
        System.out.println("Employees sorted by salary (descending):");
        employees.forEach(System.out::println);
    }
}

Output

Employees sorted by salary (descending):
Priya (Salary: 70000)
Anjali (Salary: 60000)
Rahul (Salary: 55000)
Rajesh (Salary: 45000)

Explanation

  • employees.sort((e1, e2) -> Integer.compare(e2.getSalary(), e1.getSalary())): This lambda expression sorts employees by salary in descending order by reversing the order of comparison.

Conclusion

Sorting a list of objects in Java 8 becomes simple and efficient using lambda expressions. You can sort by various attributes, such as name or salary, in ascending or descending order. Lambda expressions, combined with the Comparator interface, provide a flexible and concise way to sort lists in modern Java.

Comments