Java
Comparator
Sorting
Programming
Code Tutorial

How to use Comparator in Java to sort

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Java's Comparator interface is a key tool for sorting collections of objects when the objects' natural ordering (defined by Comparable) isn't suitable or if you want to sort based on different criteria. This article delves into using Comparator for sorting in Java, explaining its functionality and providing examples to facilitate understanding.

What is a Comparator?

The Comparator is a functional interface found in the java.util package. It provides a method for comparing two objects which can be used to dictate the order of sorting. Unlike Comparable, which sorts objects based on their "natural ordering", Comparator allows for custom sorting logic.

Key Characteristics:

  • Functional Interface: With the introduction of lambda expressions in Java 8, implementing Comparator has become more efficient.
  • Multiple Sorting Sequences: Allows sorting of objects based on different attributes.

How to Use Comparator

Step-by-Step Guide

  1. Implement the Comparator Interface: Define a class that implements the Comparator<T> interface. Override the compare method to specify the comparison logic.
java
1   import java.util.Comparator;
2
3   public class AgeComparator implements Comparator<Person> {
4       @Override
5       public int compare(Person p1, Person p2) {
6           return Integer.compare(p1.getAge(), p2.getAge());
7       }
8   }
  1. Use with Collections.sort(): Use the Collections.sort() method to sort a list of objects using the Comparator.
java
1   import java.util.ArrayList;
2   import java.util.Collections;
3   import java.util.List;
4
5   public class ComparatorExample {
6       public static void main(String[] args) {
7           List<Person> people = new ArrayList<>();
8           people.add(new Person("Alice", 30));
9           people.add(new Person("Bob", 25));
10           people.add(new Person("Charlie", 35));
11
12           Collections.sort(people, new AgeComparator());
13           for (Person person : people) {
14               System.out.println(person.getName() + " - " + person.getAge());
15           }
16       }
17   }
  1. Utilize Lambda Expressions: With Java 8 and later, you can utilize lambda expressions to simplify the use of Comparator.
java
   Collections.sort(people, (p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()));
  1. Using Comparator Factory Methods: Java 8 also introduced static factory methods in the Comparator interface, such as Comparator.comparing(), which makes comparators more concise.
java
   Collections.sort(people, Comparator.comparing(Person::getAge));
  1. Chaining Comparators: Chain multiple comparators for more complex sorting logic using thenComparing().
java
   Collections.sort(people, Comparator.comparing(Person::getAge)
                                       .thenComparing(Person::getName));

Advantages of Using Comparator

  • Flexibility: Allows for different sorting sequences.
  • Decoupled Logic: Sorting logic is separate, making Comparator implementations reusable.
  • Lambda and Method Reference Compatibility: Enhances code brevity and readability.

Example: Custom Sorting

Here is a more comprehensive example demonstrating custom sorting logic.

java
1import java.util.*;
2
3class Person {
4    private String name;
5    private int age;
6    private double salary;
7
8    public Person(String name, int age, double salary) {
9        this.name = name;
10        this.age = age;
11        this.salary = salary;
12    }
13
14    // Getters
15    public String getName() { return name; }
16    public int getAge() { return age; }
17    public double getSalary() { return salary; }
18
19    @Override
20    public String toString() {
21        return name + " - Age: " + age + ", Salary: " + salary;
22    }
23}
24
25public class ComparatorDemo {
26    public static void main(String[] args) {
27        List<Person> people = Arrays.asList(
28            new Person("Alice", 30, 70000),
29            new Person("Bob", 25, 65000),
30            new Person("Charlie", 30, 60000)
31        );
32
33        // Sorting by age, then by salary
34        people.sort(Comparator.comparing(Person::getAge)
35                              .thenComparing(Person::getSalary, Comparator.reverseOrder()));
36
37        people.forEach(System.out::println);
38    }
39}

Key Points Table

FeatureDescription
ImplementationUse the compare method.
Lambda ExpressionsSimplify comparator definitions.
Factory MethodsUtilize Comparator.comparing() for concise code.
ChainingUse thenComparing() to sort by multiple attributes.
Flexible Sorting SequencesCustomize sorting logic other than the natural order of elements.

Conclusion

The Comparator interface in Java provides an essential mechanism for customizing and controlling how objects are sorted beyond their natural ordering. Its integration with lambda expressions and method references in Java 8 further enhances its flexibility and efficiency, making it an indispensable part of Java's collection framework. By mastering the use of Comparator, developers can achieve fine-grained control over the sorting logic applicable to their applications.


Course illustration
Course illustration

All Rights Reserved.