Simply changing

public int compare(Dog d, Dog d1) {
  return d.age - d1.age;
}

to

public int compare(Dog d, Dog d1) {
  return d1.age - d.age;
}

should sort them in the reverse order of age if that is what you are looking for.

Update:

@Arian is right in his comments, one of the accepted ways of declaring a comparator for a dog would be where you declare it as a public static final field in the class itself.

class Dog implements Comparable<Dog> {
    private String name;
    private int age;

    public static final Comparator<Dog> DESCENDING_COMPARATOR = new Comparator<Dog>() {
        // Overriding the compare method to sort the age
        public int compare(Dog d, Dog d1) {
            return d.age - d1.age;
        }
    };

    Dog(String n, int a) {
        name = n;
        age = a;
    }

    public String getDogName() {
        return name;
    }

    public int getDogAge() {
        return age;
    }

    // Overriding the compareTo method
    public int compareTo(Dog d) {
        return (this.name).compareTo(d.name);
    }

}

You could then use it any where in your code where you would like to compare dogs as follows:

// Sorts the array list using comparator
Collections.sort(list, Dog.DESCENDING_COMPARATOR);

Another important thing to remember when implementing Comparable is that it is important that compareTo performs consistently with equals. Although it is not required, failing to do so could result in strange behaviour on some collections such as some implementations of Sets. See this post for more information on sound principles of implementing compareTo.

Update 2: Chris is right, this code is susceptible to overflows for large negative values of age. The correct way to implement this in Java 7 and up would be Integer.compare(d.age, d1.age) instead of d.age - d1.age.

Update 3: With Java 8, your Comparator could be written a lot more succinctly as:

public static final Comparator<Dog> DESCENDING_COMPARATOR = 
    Comparator.comparing(Dog::getDogAge).reversed();

The syntax for Collections.sort stays the same, but compare can be written as

public int compare(Dog d, Dog d1) {
    return DESCENDING_COMPARATOR.compare(d, d1);
}
Answer from Jeshurun on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
1 month ago - It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals." ... a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Top answer
1 of 6
104

Simply changing

public int compare(Dog d, Dog d1) {
  return d.age - d1.age;
}

to

public int compare(Dog d, Dog d1) {
  return d1.age - d.age;
}

should sort them in the reverse order of age if that is what you are looking for.

Update:

@Arian is right in his comments, one of the accepted ways of declaring a comparator for a dog would be where you declare it as a public static final field in the class itself.

class Dog implements Comparable<Dog> {
    private String name;
    private int age;

    public static final Comparator<Dog> DESCENDING_COMPARATOR = new Comparator<Dog>() {
        // Overriding the compare method to sort the age
        public int compare(Dog d, Dog d1) {
            return d.age - d1.age;
        }
    };

    Dog(String n, int a) {
        name = n;
        age = a;
    }

    public String getDogName() {
        return name;
    }

    public int getDogAge() {
        return age;
    }

    // Overriding the compareTo method
    public int compareTo(Dog d) {
        return (this.name).compareTo(d.name);
    }

}

You could then use it any where in your code where you would like to compare dogs as follows:

// Sorts the array list using comparator
Collections.sort(list, Dog.DESCENDING_COMPARATOR);

Another important thing to remember when implementing Comparable is that it is important that compareTo performs consistently with equals. Although it is not required, failing to do so could result in strange behaviour on some collections such as some implementations of Sets. See this post for more information on sound principles of implementing compareTo.

Update 2: Chris is right, this code is susceptible to overflows for large negative values of age. The correct way to implement this in Java 7 and up would be Integer.compare(d.age, d1.age) instead of d.age - d1.age.

Update 3: With Java 8, your Comparator could be written a lot more succinctly as:

public static final Comparator<Dog> DESCENDING_COMPARATOR = 
    Comparator.comparing(Dog::getDogAge).reversed();

The syntax for Collections.sort stays the same, but compare can be written as

public int compare(Dog d, Dog d1) {
    return DESCENDING_COMPARATOR.compare(d, d1);
}
2 of 6
31
public class DogAgeComparator implements Comparator<Dog> {
    public int compare(Dog o1, Dog o2) {
        return Integer.compare(o1.getAge(), o2.getId());
    }
}
🌐
Baeldung
baeldung.com › home › java › core java › comparator and comparable in java
Comparator and Comparable in Java | Baeldung
March 26, 2025 - Since -1 is much less than the Integer.MAX_VALUE, “Roger” should come before “John” in the sorted collection. However, due to integer overflow, the “Integer.MAX_VALUE – (-1)” will be less than zero. So based on the Comparator/Comparable contract, the Integer.MAX_VALUE is less than -1, which is obviously incorrect.
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparator-comparingint-in-java-with-examples
Comparator comparingInt() in Java with examples - GeeksforGeeks
July 11, 2025 - // Java program to demonstrate // Comparator.comparingInt(java.util.function.ToIntFunction) method import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; public class GFG { public static void main(String[] args) { // create some user objects User u1 = new User("Aaman", 25); User u2 = new User("Joyita", 22); User u3 = new User("Suvam", 28); User u4 = new User("mahafuj", 25); // before sort List<User> list = Arrays.asList(u2, u1, u4, u3); System.out.println("Before Sort:"); list.forEach(User -> System.out.println("User age " + User.getAge()));
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-comparator-interface
Java Comparator Interface - GeeksforGeeks
Returns positive integer if obj1 > obj2. ... The Collections.sort() method arranges the elements of a List based on the rules defined by a Comparator. public static <T> void sort(List<T> list, Comparator<? super T> c) The method uses the compare() ...
Published   February 2, 2026
🌐
Baeldung
baeldung.com › home › java › guide to java comparator.comparing()
Guide to Java Comparator.comparing() | Baeldung
January 8, 2024 - In this tutorial, we’ll explore several functions introduced for the Comparator interface in Java 8. For the examples in this tutorial, let’s create an Employee bean and use its fields for comparing and sorting purposes:
🌐
TutorialsPoint
tutorialspoint.com › java-integer-compare-method
Java Integer compare() method
January 6, 2025 - This can be done efficiently using the Collections.sort() method in combination with Integer.compare(). ... import java.util.*; public class IntegerCompareSortingExample { public static void main(String[] args) { List<Integer> numbers = ...
🌐
Educative
educative.io › answers › what-is-comparatorcomparingint-method-in-java
What is Comparator.comparingInt method in Java?
In line 25, we sort the list using the comparingInt method, where we create an implementation of the ToIntFunction interface that extracts the size attribute from the Packet objects.
Find elsewhere
🌐
Dev.java
dev.java › learn › writing-and-combining-comparators
Writing and Combining Comparators
February 24, 2023 - Downloading and setting up the JDK, writing your first Java class, and creating your first Java application · Launching simple source-code Java programs with the Java launcher
🌐
Readthedocs
java-8-tips.readthedocs.io › en › stable › comparator.html
7. Comparator — Java 8 tips 1.0 documentation
To compare two elements of type ... resulted keys. // Sorting words based on word lengths Function<String, Integer> keyExtractor = str -> str.length(); Stream.of("grapes", "milk", "pineapple", "water-melon") .sorted(Comparator.comparing(keyExtractor)) .forEach(System.out:...
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › Comparator.html
Comparator (Java SE 21 & JDK 21)
January 20, 2026 - It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals." ... a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
🌐
Monicagranbois
monicagranbois.com › blog › java › comparing-integers-using-integercompare-vs-subtraction
Comparing integers using Integer.compare vs subtraction
August 4, 2015 - It’s basically a conditional expression that uses comparison operations instead of subtraction: ... In the exercise, string lengths are always non-negative, so subtracting them cannot result in overflow. However, I always recommend using Integer.compare(), so that you don’t have to prove that overflow cannot occur.
🌐
Clojure
clojure.org › guides › comparators
Clojure - Comparators Guide
A 3-way comparator takes 2 values, ... 2 values, x and y, and returns true if x comes before y, or false otherwise (including if x and y are equal). < and > are good examples....
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparator-methods-and-examples
Comparator Methods and Examples - GeeksforGeeks
January 29, 2026 - Collections.sort() applies this comparator to sort the list in ascending order. public interface Comparator<T> { int compare(T o1, T o2); } Compares two objects to determine their sorting order.
🌐
Tutorialspoint
tutorialspoint.com › java › java_using_comparator.htm
Java - How to Use Comparator?
In this example, we're using Comparator interface to sort a custom object Dog based on comparison criterias. import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Dog implements Comparator<Dog>, Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { return (this.name).compareTo(d.name); } // Overriding the compare method to sort the
🌐
Dev.java
dev.java › learn › lambdas › writing-comparators
Writing and Combining Comparators - Dev.java
February 24, 2023 - Indeed, you can rewrite it in that way: Function<String, Integer> toLength = String::length; Comparator<String> comparator = (s1, s2) -> Integer.compare( toLength.apply(s1), toLength.apply(s2));
🌐
Coderanch
coderanch.com › t › 560667 › java › Understanding-Comparator
Understanding Comparator (Java in General forum at Coderanch)
December 4, 2011 - The compare(T o1, T o2) returns negative integer, zero, positive integer if the object is less than, equal to or greater than the object passed as an argument. Also the Collections.sort() internally calls, Arrays.sort which has the following logic when the comparator is passed as an argument: ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-sorted-comparator-comparator-method-java
Stream sorted (Comparator comparator) method in Java - GeeksforGeeks
December 26, 2025 - Comparators can be defined using lambda expressions, and reverse ordering can also be applied. Example: Java · import java.util.*; import java.util.stream.*; class GFG { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 2, 9, 1); numbers.stream() .sorted(Comparator.reverseOrder()) .forEach(System.out::println); } } Output ·
🌐
Oracle
docs.oracle.com › javase › 6 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 6)
For example, suppose one adds two elements a and b such that (a.equals(b) && c.compare(a, b) != 0) to an empty TreeSet with comparator c. The second add operation will return true (and the size of the tree set will increase) because a and b are not equivalent from the tree set's perspective, even though this is contrary to the specification of the Set.add method. Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap).
🌐
LabEx
labex.io › tutorials › java-comparator-and-comparable-117394
Mastering Java Comparator and Comparable | LabEx
Unsorted Student List: John, GPA: 3.5, Reg No: 101 Mary, GPA: 3.8, Reg No: 102 Alice, GPA: 3.2, Reg No: 103 Bob, GPA: 3.9, Reg No: 104 Students sorted by name (using Comparator): Alice, GPA: 3.2, Reg No: 103 Bob, GPA: 3.9, Reg No: 104 John, GPA: 3.5, Reg No: 101 Mary, GPA: 3.8, Reg No: 102 · As you can see, the students are now sorted alphabetically by name, rather than by GPA. Java 8 introduced lambda expressions, which can simplify creating comparators.