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
🌐
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 ·
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());
    }
}
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-comparator-interface
Java Comparator Interface - GeeksforGeeks
Java 8 introduced a more simple way to write comparators using lambda expressions. We can use the method mentioned below for achieving same result: ... import java.util.*; // Define the Student class class Student { String name; Integer age; // Constructor Student(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public Integer getAge() { return age; } // Method to print student details @Override public String toString() { return name + " : " + age; } } public class ComparatorHelperClassExample { public static void main(String[] args) { Li
Published   February 2, 2026
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
1 month ago - This interface is a member of the Java Collections Framework. ... Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
🌐
TutorialsPoint
tutorialspoint.com › java-integer-compare-method
Java Integer compare() method
January 6, 2025 - The Integer.compare() method is a simple and effective way to compare integers in Java. It is especially useful in sorting and when working with collections.
🌐
Readthedocs
java-8-tips.readthedocs.io › en › stable › comparator.html
7. Comparator — Java 8 tips 1.0 documentation
To compare two elements of type T, it first applies the key extracting function to both the elements and then performs the sorting operation on the 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::println);
🌐
Tutorialspoint
tutorialspoint.com › java › java_using_comparator.htm
Java - How to Use Comparator?
By overriding compare(), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.
🌐
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()));
Find elsewhere
🌐
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.
🌐
Baeldung
baeldung.com › home › java › core java › comparator and comparable in java
Comparator and Comparable in Java | Baeldung
March 26, 2025 - We can define multiple different comparison strategies, which isn’t possible when using Comparable · Over the course of this tutorial, we’ve used the Integer.compare() method to compare two integers.
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparator-methods-and-examples
Comparator Methods and Examples - GeeksforGeeks
January 29, 2026 - A Comparator is implemented using a lambda expression to define custom sorting logic for integers. Collections.sort() applies this comparator to sort the list in ascending order. public interface Comparator<T> { int compare(T o1, T o2); } Compares ...
🌐
Educative
educative.io › answers › what-is-comparatorcomparingint-method-in-java
What is Comparator.comparingInt method in Java?
comparingInt is a static method of the Comparator that sorts a list of elements of any type using an integer sort key. The sort key is extracted with the help of the ToIntFunction functional interface, whose implementation is passed as a parameter ...
🌐
Oracle
docs.oracle.com › javase › 6 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 6)
This interface is a member of the Java Collections Framework. ... Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
🌐
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 - Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
🌐
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.
🌐
Dev.java
dev.java › learn › lambdas › writing-comparators
Writing and Combining Comparators - Dev.java
February 24, 2023 - Suppose you need to create a comparator to compare strings of characters in a non-natural way: the shortest strings are lesser than the longest strings. ... You learned in the previous part that it is possible to chain and compose lambda expressions. This code is another example of such a composition. 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));
🌐
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
🌐
DigitalOcean
digitalocean.com › community › tutorials › comparable-and-comparator-in-java-example
Comparable and Comparator in Java: Examples & Guide | DigitalOcean
August 3, 2022 - Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. The Comparable interface has compareTo(T obj) method which is used by sorting methods, you can check any Wrapper, String or Date class to confirm this.
🌐
Javatpoint
javatpoint.com › Comparator-interface-in-collection-framework
Java Comparator - javatpoint
Java Comparator interface is used to order the user-defined class objects, compare() method, collection class, java comporator example, Example of Comparator interface in collection framework.
🌐
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.