Test implements Comparator and override compare() method

  public class Test implements Comparator<Test>{
    private int    priority;
    private String desciption;

    @Override
    public int compare(Test o1, Test o2) {
       // your code here
    }

  }
Answer from Ruchira Gayan Ranaweera on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › comparator and comparable in java
Comparator and Comparable in Java | Baeldung
March 26, 2025 - We can build one simply by making use of the Comparator or Comparable interfaces. Let’s use an example of a football team, where we want to line up the players by their rankings. ... public class Player { private int ranking; private String name; private int age; // constructor, getters, setters } Next, we’ll create a PlayerSorter class to create our collection, and attempt to sort it using Collections.sort:
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-comparator-interface
Java Comparator Interface - GeeksforGeeks
Comparator.comparing() creates comparator by name.
Published   February 2, 2026
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
3 weeks ago - Java™ Platform Standard Ed. 8 ... This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface Comparator<T> A comparison function, which imposes a total ordering on some collection of objects.
🌐
Tutorialspoint
tutorialspoint.com › java › java_using_comparator.htm
Java - How to Use Comparator?
The Comparator interface defines two methods: compare() and equals(). The compare() method, shown here, compares two elements for order − ... obj1 and obj2 are the objects to be compared.
🌐
DigitalOcean
digitalocean.com › community › tutorials › comparable-and-comparator-in-java-example
Comparable and Comparator in Java: Examples & Guide | DigitalOcean
August 3, 2022 - Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if the first argument is less than the second one and returns zero if they are equal and positive int if the first ...
🌐
Oracle
docs.oracle.com › cd › E19182-01 › 821-0919 › ref_sme-custom1_c › index.html
Step 1: Create the Custom Comparator Java Class (Master Index Match Engine Reference)
Documentation Home > Master Index ... The first step to creating custom comparators is defining the matching logic in custom comparator Java classes that are stored in the real-time module of the Master Index Match Engine....
Top answer
1 of 3
7

First of all, this question seems to be more appropriate for Code Review. But there are some concepts to explain that go beyond code review, so I decided to post an answer.

First draft

Your comparator can be considered as a first draft. It is working well and compares two Date objects as specified. Well done.

Code improvement

The many if-else-statements make the comparator somewhat clumsy and unreadable. Keep in mind that the compare method is not bound to returning -1, 0, or 1. It can return any negative number if the first argument is less than the second one, and any positive number if the first argument is greater than the second one. Only the 0 return is bound to equality.

As month and day are both represented as integers, you can simply use them in a little arithmetic. The month difference is more important - it weighs more - so it must be heavier:

public int compare(Date date1, Date date2) {
    int monthDiff = date1.getMonth() - date2.getMonth();
    int dayDiff = date1.getDay() - date2.getDay();
    return monthDiff * 100 + dayDiff;
}

Subtractions already produce a negative number, a zero, or a positive number. So use them. The factor 100 makes the month difference more important than the day difference.

If the month difference is not 0, then adding the day difference will not have any effect (because of the factor 100). Only when the month difference is 0, then the day difference will be important.

Code structure

Comparing two dates this way looks very natural. In fact, this is a natural ordering on dates. If a type has such a natural ordering, you should (must) let it implement Comparable:

public class Date implements Comparable<Date> {
    ...
    @Override
    public int compareTo(Date other) {
        int monthDiff = this.getMonth() - other.getMonth();
        int dayDiff = this.getDay() - other.getDay();
        return monthDiff * 100 + dayDiff;
    }
}

Other comparators

If you feel that you must have some other comparators, you can always add them. A good place is a nested static class inside your Date class (as they simply belong to it).

Let's make a comparator that only take the month into account:

public class Date implements Comparable<Date> {
    ...
    public static final class MonthComparator implements Comparator<Date> {
        @Override
        public int compare(Date date1, Date date2) {
            return date1.getMonth() - date2.getMonth();
        }
    }
}
2 of 3
0

his is one (almost) correct way to do it. I write almost because any of the two Dates may be null, and you should probably check for that.

Apart from that, it seems good enough.

Find elsewhere
🌐
Dev.java
dev.java › learn › lambdas › writing-comparators
Writing and Combining Comparators - Dev.java
February 24, 2023 - Now you can see that the code of this Comparator only depends on the Function called toLength. So it becomes possible to create a factory method that takes this function as an argument and returns the corresponding Comparator<String>.
🌐
Dev.java
dev.java › learn › writing-and-combining-comparators
Writing and Combining Comparators
February 24, 2023 - Downloading and setting up the ... and creating your first Java application. ... Launching simple source-code Java programs with the Java launcher. ... jshell interactively evaluates declarations, statements, and expressions of the Java programming language in a read-eval-print loop (REPL).
🌐
Oracle
docs.oracle.com › javase › › 7 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 7 )
Java™ Platform Standard Ed. 7 ... A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
🌐
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.
🌐
Medium
medium.com › @tuananhbk1996 › how-to-write-a-custom-comparator-function-in-java-5642a48b45cf
How to Write a Custom Comparator Function in Java? | by Anh Trần Tuấn | Medium
November 16, 2024 - Let’s walk through the process of creating a custom Comparator. Consider a class Employee with fields name, age, and salary. We want to sort a list of Employee objects by salary in ascending order. import java.util.Comparator; class Employee { private String name; private int age; private double salary; // Constructor, getters, and setters public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public double getSalary() { return salary; } @Override public String toString() { return "Employee{" + "name='" + name + ''' + ", age=" + age + ", salary=" + salary + '}'; } } class SalaryComparator implements Comparator<Employee> { @Override public int compare(Employee e1, Employee e2) { return Double.compare(e1.getSalary(), e2.getSalary()); } }
🌐
BtechSmartClass
btechsmartclass.com › java › java-Comparators.html
Java Tutorials - Comparators in java
Step - 6: Call the sort method of Collections class by passing the object created in step - 6. Step - 7: Use a for-each (any loop) to print the sorted information. Let's consider an example program to illustrate Comparator using a separate class. ... import java.util.*; class Student{ String name; float percentage; Student(String name, float percentage){ this.name = name; this.percentage = percentage; } } class PercentageComparator implements Comparator<Student>{ public int compare(Student stud1, Student stud2) { if(stud1.percentage < stud2.percentage) return 1; return -1; } } public class Stu
🌐
Blogger
javarevisited.blogspot.com › 2014 › 01 › java-comparator-example-for-custom.html
Java Comparator Example for Custom Sorting Employee by Name, Age and Salary
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online. Here is the complete code of creating different Comparator classes to compare objects on different attributes.
🌐
CalliCoder
callicoder.com › java-comparable-comparator
Java Comparable and Comparator interface examples | CalliCoder
February 18, 2022 - When you define the compareTo() method in your classes, you need to make sure that the return value of this method is - negative, if this object is less than the supplied object. zero, if this object is equal to the supplied object. positive, if this object is greater than the supplied object. Many predefined Java classes like String, Date, LocalDate, LocalDateTime etc implement the Comparable interface to define the ordering of their instances.
Top answer
1 of 9
117

I recommend you create an enum for your car colours instead of using Strings and the natural ordering of the enum will be the order in which you declare the constants.

public enum PaintColors {
    SILVER, BLUE, MAGENTA, RED
}

and

 static class ColorComparator implements Comparator<CarSort>
 {
     public int compare(CarSort c1, CarSort c2)
     {
         return c1.getColor().compareTo(c2.getColor());
     }
 }

You change the String to PaintColor and then in main your car list becomes:

carList.add(new CarSort("Ford Figo",PaintColor.SILVER));

...

Collections.sort(carList, new ColorComparator());
2 of 9
82

How about this:

List<String> definedOrder = // define your custom order
    Arrays.asList("Red", "Green", "Magenta", "Silver");

Comparator<Car> comparator = new Comparator<Car>(){

    @Override
    public int compare(final Car o1, final Car o2){
        // let your comparator look up your car's color in the custom order
        return Integer.valueOf(
            definedOrder.indexOf(o1.getColor()))
            .compareTo(
                Integer.valueOf(
                    definedOrder.indexOf(o2.getColor())));
    }
};

In principle, I agree that using an enum is an even better approach, but this version is more flexible as it lets you define different sort orders.

Update

Guava has this functionality baked into its Ordering class:

List<String> colorOrder = ImmutableList.of("red","green","blue","yellow");
final Ordering<String> colorOrdering = Ordering.explicit(colorOrder);
Comparator<Car> comp = new Comparator<Car>() {
    @Override
    public int compare(Car o1, Car o2) {
        return colorOrdering.compare(o1.getColor(),o2.getColor());
    }
}; 

This version is a bit less verbose.


Update again

Java 8 makes the Comparator even less verbose:

Comparator<Car> carComparator = Comparator.comparing(
        c -> definedOrder.indexOf(c.getColor()));
🌐
LabEx
labex.io › tutorials › java-how-to-compare-objects-with-custom-comparator-in-java-419620
How to compare objects with custom comparator in Java | LabEx
It provides a way to compare two objects and determine their order, which is particularly useful when you want to sort collections or implement custom sorting mechanisms. The Comparator interface contains a single abstract method: ... import java.util.Comparator; public class IntegerComparatorExample { public static void main(String[] args) { Comparator<Integer> ascendingComparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }; // Using lambda expression (Java 8+) Comparator<Integer> descendingComparator = (o1, o2) -> o2.compareTo(o1); } }
🌐
Codecademy
codecademy.com › docs › java › comparator
Java | Comparator | Codecademy
July 28, 2025 - You can utilize lambda expressions to implement comparators in Java concisely. ... Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more! ... Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
🌐
HappyCoders.eu
happycoders.eu › java › comparator-comparable-compareto
compareTo, Comparable, Comparator - Comparing Objects in Java
June 12, 2025 - To sort objects, the program has to compare them and find out if one object is smaller, larger, or equal to another. You can find the article's source code in this GitHub repository. You compare Java primitives (int, long, double, etc.) using the operators <, <=, ==, =>, >.