1. Introduction

In Java, the Comparator interface is used tool for defining custom orderings for collections of objects. Sometimes, we need to sort based on multiple attributes of an object. For example, consider sorting a list of employees first by their age and then by their name. In this post, we will demonstrate how to achieve this by chaining multiple comparators using the thenComparing() method.

2. Program Steps

1. Define an Employee class with attributes like name and age.

2. Create a list of Employee objects.

3. Define a comparator to sort by age.

4. Chain this comparator with another comparator to sort by name using thenComparing().

5. Sort the list of employees using the chained comparator.

6. Print the sorted list.

3. Code Program

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

class Employee {
    String name;
    int age;

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

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

public class MultiFieldComparatorDemo {

    public static void main(String[] args) {
        // Create a list of employees
        List<Employee> employees = Arrays.asList(
                new Employee("John", 25),
                new Employee("Jane", 30),
                new Employee("Doe", 25),
                new Employee("Smith", 30)
        );

        System.out.println("Original list: " + employees);

        // Sort employees by age, then by name
        employees.sort(Comparator.comparingInt(Employee::getAge)
                                 .thenComparing(Employee::getName));

        System.out.println("Sorted by age, then by name: " + employees);
    }
}

Output:

Original list: [John (25), Jane (30), Doe (25), Smith (30)]
Sorted by age, then by name: [Doe (25), John (25), Jane (30), Smith (30)]

4. Step By Step Explanation

1. We define an Employee class with attributes name and age and provide an appropriate toString() method for easy printing.

2. In the main method, we create a list of Employee objects.

3. Next, we define a comparator to sort employees based on their age using Comparator.comparingInt().

4. We then chain this comparator with another one to sort employees by their name in case of age ties. This is achieved using the thenComparing() method.

5. Using this chained comparator, we sort the list of employees.

6. The output demonstrates that the list is first sorted by age, and where the age is the same, it's sorted by name.

By chaining comparators, we can create complex sorting logic while keeping the code clean and readable.