Java Comparator Example

In this article, we will discuss how to use the Comparator interface in Java to compare and sort objects. We will cover various ways to implement the Comparator interface and provide examples to demonstrate its usage.

Table of Contents

  1. Introduction
  2. Implementing Comparator with an Anonymous Class
  3. Implementing Comparator with a Lambda Expression
  4. Implementing Comparator with Method References
  5. Sorting a List Using Comparator
  6. Complete Example
  7. Conclusion

Introduction

The Comparator interface in Java is used to define a custom comparison logic for objects. It is part of the java.util package and provides a way to order the objects of a user-defined class. The interface has two main methods:

  • compare(T o1, T o2): Compares its two arguments for order.
  • equals(Object obj): Indicates whether some other object is "equal to" this comparator (optional).

Implementing Comparator with an Anonymous Class

One way to implement the Comparator interface is by using an anonymous class.

Example

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

public class ComparatorAnonymousClassExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Cherry");

        // Implementing Comparator using an anonymous class
        Comparator<String> comparator = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        };

        Collections.sort(fruits, comparator);
        System.out.println("Sorted fruits: " + fruits);
    }
}

Output:

Sorted fruits: [Apple, Banana, Cherry]

Implementing Comparator with a Lambda Expression

Java 8 introduced lambda expressions, which provide a concise way to implement the Comparator interface.

Example

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

public class ComparatorLambdaExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Cherry");

        // Implementing Comparator using a lambda expression
        Comparator<String> comparator = (o1, o2) -> o1.compareTo(o2);

        Collections.sort(fruits, comparator);
        System.out.println("Sorted fruits: " + fruits);
    }
}

Output:

Sorted fruits: [Apple, Banana, Cherry]

Implementing Comparator with Method References

Method references provide another way to implement the Comparator interface in a more readable and concise manner.

Example

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

public class ComparatorMethodReferenceExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Cherry");

        // Implementing Comparator using method reference
        Comparator<String> comparator = String::compareTo;

        Collections.sort(fruits, comparator);
        System.out.println("Sorted fruits: " + fruits);
    }
}

Output:

Sorted fruits: [Apple, Banana, Cherry]

Sorting a List Using Comparator

You can sort a list of custom objects by implementing the Comparator interface for the custom class.

Example

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

class Student {
    String name;
    int age;

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

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + '}';
    }
}

public class SortCustomObjectsExample {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("John", 22));
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 21));

        // Implementing Comparator to sort students by age
        Comparator<Student> byAge = (s1, s2) -> Integer.compare(s1.age, s2.age);

        Collections.sort(students, byAge);
        System.out.println("Sorted students by age: " + students);
    }
}

Output:

Sorted students by age: [Student{name='Alice', age=20}, Student{name='Bob', age=21}, Student{name='John', age=22}]

Complete Example

Here's a complete example that demonstrates various ways to use the Comparator interface to sort a list of custom objects by different criteria.

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

class Student {
    String name;
    int age;

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

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + '}';
    }
}

public class ComparatorExample {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("John", 22));
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 21));

        // Sort students by age using an anonymous class
        Comparator<Student> byAge = new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return Integer.compare(s1.age, s2.age);
            }
        };

        Collections.sort(students, byAge);
        System.out.println("Sorted students by age (anonymous class): " + students);

        // Sort students by name using a lambda expression
        Comparator<Student> byName = (s1, s2) -> s1.name.compareTo(s2.name);

        Collections.sort(students, byName);
        System.out.println("Sorted students by name (lambda): " + students);

        // Sort students by age using method reference
        Comparator<Student> byAgeMethodRef = Comparator.comparingInt(s -> s.age);

        Collections.sort(students, byAgeMethodRef);
        System.out.println("Sorted students by age (method reference): " + students);
    }
}

Output:

Sorted students by age (anonymous class): [Student{name='Alice', age=20}, Student{name='Bob', age=21}, Student{name='John', age=22}]
Sorted students by name (lambda): [Student{name='Alice', age=20}, Student{name='Bob', age=21}, Student{name='John', age=22}]
Sorted students by age (method reference): [Student{name='Alice', age=20}, Student{name='Bob', age=21}, Student{name='John', age=22}]

Conclusion

Using the Comparator interface in Java allows you to define custom comparison logic for sorting objects. Java 8 introduced lambda expressions and method references, which make it easier and more concise to implement comparators. This guide provided examples of using anonymous classes, lambda expressions, and method references to sort objects. By understanding these concepts, you can efficiently sort collections of custom objects in your applications.

Comments