Java Comparator Interface with Lambda Expressions Example

Lambda expressions provide a concise and readable way to implement Comparator logic without the need for anonymous inner classes.

Java Comparator Interface with Lambda Expressions

Here's a demonstration showcasing the use of Comparator in conjunction with lambda expressions:

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

class Student {
    String name;
    int age;

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

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

public class ComparatorLambdaDemo {
    public static void main(String[] args) {
        Student[] students = {
            new Student("Rohan", 20),
            new Student("Amit", 22),
            new Student("Pooja", 19)
        };

        // 1. Sorting by age using lambda
        Arrays.sort(students, (s1, s2) -> s1.age - s2.age);
        System.out.println("Students sorted by age: " + Arrays.toString(students));

        // 2. Sorting by name using lambda
        Arrays.sort(students, (s1, s2) -> s1.name.compareTo(s2.name));
        System.out.println("Students sorted by name: " + Arrays.toString(students));

        // 3. Sorting by age in descending order using lambda
        Arrays.sort(students, (s1, s2) -> s2.age - s1.age);
        System.out.println("Students sorted by age in reverse: " + Arrays.toString(students));
    }
}

Output:

Students sorted by age: [Pooja (19), Rohan (20), Amit (22)]
Students sorted by name: [Amit (22), Pooja (19), Rohan (20)]
Students sorted by age in reverse: [Amit (22), Rohan (20), Pooja (19)]

Explanation:

1. Sorting by age: We are using a lambda expression (s1, s2) -> s1.age - s2.age to compare the age of two student objects. If the result is negative, s1 is younger than s2, if positive s1 is older, and if zero, they are of the same age.

2. Sorting by name: The lambda (s1, s2) -> s1.name.compareTo(s2.name) leverages the compareTo method from the String class to compare the names alphabetically.

3. Sorting by age in descending order: The lambda (s1, s2) -> s2.age - s1.age sorts the students by age in descending order. Notice how the order of subtraction is reversed compared to the ascending order comparator.


Comments