Reading history

Java Comparable and Comparator: Sorting Objects

5 min read 0 views

Sort custom objects in Java with Comparable and compareTo, and Comparator.comparing, reversed and thenComparing for multi-key sorting, with tested examples.

Java can sort numbers and strings by itself, but it does not know how to sort your own objects. Should students be ordered by name, by CGPA, or by department and then CGPA? Java gives you two tools to answer that. Comparable lets a class define its one natural order. Comparator defines any number of other orders from outside the class. This lesson uses both, including the modern Comparator.comparing style.

In this lesson you will learn

  • Implementing Comparable and compareTo
  • What negative, zero and positive results mean
  • Building comparators with Comparator.comparing
  • Reversing and chaining with reversed() and thenComparing
  • When to use Comparable and when to use Comparator

You should know ArrayList and lambda expressions.

Comparable: the Natural Order

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

public class Main {
    // Comparable: the class defines its own "natural" order
    static class Student implements Comparable<Student> {
        String name;
        double cgpa;
        Student(String name, double cgpa) { this.name = name; this.cgpa = cgpa; }

        @Override
        public int compareTo(Student other) {
            return this.name.compareTo(other.name);      // alphabetical by name
        }

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

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>(List.of(
                new Student("Tania", 3.95), new Student("Arif", 3.41),
                new Student("Nusrat", 3.82), new Student("Mitu", 3.67)));

        Collections.sort(list);                          // uses compareTo
        System.out.println(list);

        Student a = list.get(0), n = list.get(2);
        System.out.println("Arif vs Nusrat: " + a.compareTo(n));
        System.out.println("Nusrat vs Arif: " + n.compareTo(a));
        System.out.println("Arif vs Arif: " + a.compareTo(a));
    }
}

Output

[Arif(3.41), Mitu(3.67), Nusrat(3.82), Tania(3.95)]
Arif vs Nusrat: -13
Nusrat vs Arif: 13
Arif vs Arif: 0
  • implements Comparable<Student> promises a compareTo method. Collections.sort, TreeSet and TreeMap all use it.
  • a.compareTo(b) returns a negative number if a comes first, zero if they are equal in order, and a positive number if a comes after b. Only the sign matters, not the size: -13 just means “before”.
  • Here the natural order is alphabetical by name, so the list is sorted Arif, Mitu, Nusrat, Tania.
  • Use Comparable when there is one obvious order for the type, like numbers, dates or names.

Comparator: Any Order You Need

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    record Student(String name, String dept, double cgpa) {}

    static String names(List<Student> list) {
        return list.stream().map(Student::name).collect(Collectors.joining(" "));
    }

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>(List.of(
                new Student("Tania", "CSE", 3.95), new Student("Arif", "EEE", 3.41),
                new Student("Nusrat", "CSE", 3.82), new Student("Rafi", "EEE", 2.98),
                new Student("Mitu", "CSE", 3.67)));

        // Comparator: an order defined outside the class
        list.sort(Comparator.comparingDouble(Student::cgpa).reversed());
        System.out.println(names(list));

        // Several keys: department, then CGPA high to low
        list.sort(Comparator.comparing(Student::dept)
                .thenComparing(Student::cgpa, Comparator.reverseOrder()));
        System.out.println(list.stream().map(s -> s.dept() + ":" + s.name())
                .collect(Collectors.joining(" ")));

        // Old-style anonymous comparator, by name length then name
        list.sort(new Comparator<Student>() {
            @Override
            public int compare(Student x, Student y) {
                int byLength = Integer.compare(x.name().length(), y.name().length());
                return byLength != 0 ? byLength : x.name().compareTo(y.name());
            }
        });
        System.out.println(names(list));

        System.out.println(list.stream().max(Comparator.comparingDouble(Student::cgpa)).get().name());
    }
}

Output

Tania Nusrat Mitu Arif Rafi
CSE:Tania CSE:Nusrat CSE:Mitu EEE:Arif EEE:Rafi
Arif Mitu Rafi Tania Nusrat
Tania
  • Comparator.comparingDouble(Student::cgpa) builds a comparator from a key: “compare students by their CGPA”. .reversed() turns it into highest first.
  • thenComparing adds a tie-breaker. Students are grouped by department, and within each department sorted by CGPA from high to low.
  • The third sort shows the older style: an anonymous class with a compare(x, y) method. It sorts by name length, then alphabetically. The lambda style above does the same job in less code.
  • Comparators work everywhere an order is needed: list.sort, stream().max, TreeMap and PriorityQueue.
  • Integer.compare(a, b) is the safe way to compare numbers inside compare. The shortcut a - b can overflow for large or negative values.

Comparable vs Comparator

ComparableComparator
Packagejava.langjava.util
MethodcompareTo(T other)compare(T a, T b)
Where it livesInside the class being sortedOutside, as a separate object or lambda
How many ordersOne natural orderAs many as you like
Used byCollections.sort(list), TreeSetlist.sort(cmp), new TreeSet<>(cmp)

Common Mistakes

  1. Returning a - b from a comparison; it can overflow. Use Integer.compare or Comparator.comparingInt.
  2. Making compareTo disagree with equals. A TreeSet treats elements that compare as 0 as duplicates and keeps only one.
  3. Sorting a List.of(...) list, which is unmodifiable and throws an exception. Copy it into an ArrayList first.
  4. Forgetting null values; use Comparator.nullsFirst or nullsLast when a key can be null.

Practice Exercises

Exercise 1. Sort the students by name length, shortest first, using Comparator.comparingInt.

Show answer
list.sort(Comparator.comparingInt(s -> s.name().length()));

The sort is stable, so students with names of equal length keep their previous relative order.

Exercise 2. Create a TreeSet of strings that ignores case, so “Dhaka” and “dhaka” count as the same city.

Show answer
TreeSet<String> cities = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
cities.add("Dhaka");
cities.add("dhaka");
cities.add("Sylhet");
System.out.println(cities);   // [Dhaka, Sylhet]

Frequently Asked Questions

Is Java’s sort stable?

Yes for objects. List.sort and Collections.sort keep equal elements in their original order, which is what makes sorting by one key and then another work as expected.

Can a record implement Comparable?

Yes. A record can implement any interface: record Student(String name, double cgpa) implements Comparable<Student>, with a compareTo method in its body.

Summary

  • Comparable gives a class its natural order through compareTo.
  • Comparator defines extra orders outside the class.
  • Build comparators with comparing, reversed and thenComparing.
  • Compare numbers with Integer.compare, never subtraction.

Next: Java Queue, Deque and PriorityQueue.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *