Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since java-8

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

Answer from Michael Myers on Stack Overflow
Top answer
1 of 16
1737

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since java-8

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

2 of 16
202

Classes that has a natural sort order (a class Number, as an example) should implement the Comparable interface, whilst classes that has no natural sort order (a class Chair, as an example) should be provided with a Comparator (or an anonymous Comparator class).

Two examples:

public class Number implements Comparable<Number> {
    private int value;

    public Number(int value) { this.value = value; }
    public int compareTo(Number anotherInstance) {
        return this.value - anotherInstance.value;
    }
}

public class Chair {
    private int weight;
    private int height;

    public Chair(int weight, int height) {
        this.weight = weight;
        this.height = height;
    }
    /* Omitting getters and setters */
}
class ChairWeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getWeight() - chair2.getWeight();
    }
}
class ChairHeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getHeight() - chair2.getHeight();
    }
}

Usage:

List<Number> numbers = new ArrayList<Number>();
...
Collections.sort(numbers);

List<Chair> chairs = new ArrayList<Chair>();
// Sort by weight:
Collections.sort(chairs, new ChairWeightComparator());
// Sort by height:
Collections.sort(chairs, new ChairHeightComparator());

// You can also create anonymous comparators;
// Sort by color:
Collections.sort(chairs, new Comparator<Chair>() {
    public int compare(Chair chair1, Chair chair2) {
        ...
    }
});
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-arraylist-of-object-sort-example-comparable-and-comparator
Java ArrayList of Object Sort Example (Comparable And Comparator)
Let’s say we need to sort the ArrayList<Student> based on the student Age property. This is how it can be done – First implement Comparable interface and then Override the compareTo method.
Discussions

Please help me understand how is this custom comparator sorting the array
Technically, you'll create a new Class like: public class ArrayComparator implements Comparator { @Override public int compare(int[] obj1, int[] obj2) { if(obj1[0] < obj2[0]) return -1; //Whichever returns a negative number will be on top else if(obj1[0] == obj2[0]) return 0; //In your example, they're checking the second number as well else return 1; } } And then use it like: Arrays.sort(people, new ArrayComparator()); What they're doing is instead of creating a new class and then using it's object, they're using an Anonymous class (class with no name) that implements Comparator on the spot. Also Comparator is an interface. Look into how interfaces work. They can also be used as types. More on reddit.com
🌐 r/learnjava
7
4
March 26, 2020
java - Sorting ArrayList by LocalDate with custom Comparator - Stack Overflow
I deserialize some Json and put it into a model with the following structure: Model: import java.time.LocalDate; public class MyClass implements Serializable { String name; LocalDate da... More on stackoverflow.com
🌐 stackoverflow.com
Sorting 2D arrays by rows in Java using comparators
This is lambda expression in Java. Basically what it does is just sort two arrays by their first element More on reddit.com
🌐 r/leetcode
2
2
July 24, 2021
6 Advanced Comparator and Comparable Examples in Java 8 for Sorting ArrayList Objects By Fields
That page has way too much breaking up the flow of the page, at least on mobile. It's somewhat ironic that the thumbnail doesn't use Comparator. Array.sort(testStrings, comparing(String::length)); More on reddit.com
🌐 r/java
1
13
September 15, 2021
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-sort-arraylist-using-comparator
How to Sort ArrayList using Comparator? - GeeksforGeeks
July 23, 2025 - // Java program to Sort ArrayList using Comparator import java.util.*; // create the Shop class class Shop { int ProductNo; String name; int stock; // constructor Shop(int ProductNo, String name, int stock) { this.ProductNo = ProductNo; this.name = name; this.stock = stock; } } // creates the comparator for comparing name class NameComparator implements Comparator<Shop> { // override the compare() method public int compare(Shop s1, Shop s2) { return s1.name.compareTo(s2.name); } } class GFG { public static void main(String[] args) { // create the ArrayList object ArrayList<Shop> s = new ArrayL
🌐
Java67
java67.com › 2017 › 07 › how-to-sort-arraylist-of-objects-using.html
How to Sort ArrayList of Objects by Fields in Java? Custom + Reversed Order Sorting Comparator Example | Java67
The Comparable interface provides natural order like the lexicographic order of String or name for Employees, while Comparator is used to provide custom order. It gives you the flexibility to sort your objects on the parameter you want e.g. ...
🌐
W3Schools
w3schools.com › java › java_advanced_sorting.asp
Java Advanced Sorting (Comparator and Comparable)
For example, if you have a list of cars you might want to sort them by year, the rule could be that cars with an earlier year go first. The Comparator and Comparable interfaces allow you to specify what rule is used to sort objects.
🌐
Blogger
javarevisited.blogspot.com › 2012 › 01 › how-to-sort-arraylist-in-java-example.html
How to sort ArrayList in Natural and Custom Order in Java - Example Tutorial
To sort an ArrayList in Java on Custom order we need to supply an external Comparator along with ArrayList to Collections.sort(List, Comparator) method. compare() method will define how the sorting of objects will take place in ArrayList.
🌐
Gitbook
gyansetu-core-java-for-java.gitbook.io › project › untitled-1 › creating-and-using-list-set-and-deque-implementations › custom-sorting-using-comparator
Custom Sorting using comparator | Core java - Advance Topics
May 9, 2019 - For such cases, Java provides a Comparator interface. You can define a Comparator and pass it to the sorting functions like Collections.sort or Arrays.sort to sort the objects based on the ordering defined by the Comparator.
Find elsewhere
🌐
Vultr Docs
docs.vultr.com › java › examples › sort-arraylist-of-custom-objects-by-property
Java Program to Sort ArrayList of Custom Objects By Property | Vultr Docs
December 19, 2024 - The output will list the names in alphabetical order: Alice, Bob, Steve. Create a comparator class that implements Comparator<Employee>. Customize the compare method to sort based on a different attribute, such as employee ID.
🌐
Reddit
reddit.com › r/learnjava › please help me understand how is this custom comparator sorting the array
r/learnjava on Reddit: Please help me understand how is this custom comparator sorting the array
March 26, 2020 -

So i have 2d array like this:-

[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]

each element of the array is a pair (h, k)

Now the below code sorts this array in a form when comparing two pairs if h is same then sort based on k in ascending order. But if h of two pairs is not the same then sort descendingly based on h.

Code:-

Arrays.sort(people, new Comparator<int[]>(){
          Override
           public int compare(int[] o1, int[] o2) {
               return (o1[0] == o2[0]) ? o1[1] - o2[1] : o2[0] - o1[0];
               // how is the return statement working??
           } 
            
 });

I encountered this while solving a leetcode question. I cannot figure out this code in the solution as i haven't worked with a custom comparator before. Thank you.

🌐
Java Training School
javatrainingschool.com › home › sorting arraylist using comparator
Sorting ArrayList using Comparator - Java Training School
April 13, 2024 - ID comparator class that sorts based on Cricketer id · package com.javatrainingschool; import java.util.Comparator; public class IDComparator implements Comparator<Cricketer>{ @Override public int compare(Cricketer c1, Cricketer c2) { int result = 0; result = Integer.valueOf(c1.getId()).compareTo(c2.getId()); return result; } } ... package com.javatrainingschool; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArrayListSortingExample { public static void main(String[] args) { List<Cricketer> cricketerList = new ArrayList<Cricketer>(); Cricketer c1
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › java arraylist sort: ascending and descending order
Java ArrayList Sort: Ascending and Descending Order
August 4, 2023 - For custom ordering, we can create Comparator instances having the appropriate sorting logic. For example, we can sort the tasks by the name field. Comparators are useful when the element (to be stored in the list) does not implement the Comparable ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-sort-an-arraylist-of-objects-by-property-in-java
How to Sort an ArrayList of Objects by Property in Java? - GeeksforGeeks
July 23, 2025 - When the ArrayList is of a custom object type, then, in this case, we use two sorting methods by either Comparator or Comparable and in this case Collections.sort() cannot be used directly as it will give an error because it sorts only specific data-types and not user-defined types.
🌐
Medium
medium.com › @sujathamudadla1213 › implement-a-custom-comparator-to-sort-a-list-of-custom-objects-1a77b5ddc662
Implement a custom Comparator to sort a list of custom objects. - Sujatha Mudadla - Medium
July 17, 2023 - public class CustomObjectSorting { public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person(“Alice”, 30)); people.add(new Person(“Bob”, 25)); people.add(new Person(“Charlie”, 35)); // Sort by age in ascending order people.sort(Comparator.comparingInt(p -> p.getAge())); System.out.println(people); } } 2.5K followers ·
🌐
Vultr
docs.vultr.com › java › standard library › java › util › arraylist › sort()
Java ArrayList sort() - Order Elements
November 15, 2024 - Sort an ArrayList of these objects using the custom comparator. ... import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return this.name + " - " + this.age; } } ArrayList<Person> people = new ArrayList<>(); people.add(new Person("John", 30)); people.add(new Person("Alice", 24)); people.add(new Person("Bob", 27)); Collections.sort(people, new Comparator<Person>() { public int compare(Person p1, Person p2) { return Integer.compare(p1.age, p2.age); } }); System.out.println(people);
🌐
How to do in Java
howtodoinjava.com › home › java sorting › java collections sort()
Java Collections sort() - HowToDoInJava
December 14, 2022 - ArrayList<Employee> employees = ... comparison logic with the help of comparators and then we can use sort() method to sort the list based on the given custom logic....
🌐
Medium
medium.com › @thecodebean › java-object-sorting-explained-using-comparable-and-comparator-03b93b988f75
Java Object Sorting Using Comparable and Comparator | The Code Bean | Medium
October 21, 2023 - You can use Comparator instances to sort objects, search for specific objects in a list, or define custom sorting orders without modifying the object classes themselves.
🌐
Blogger
javahungry.blogspot.com › 2017 › 11 › java-arraylist-of-object-sort-example-comparable-comparator.html
Java ArrayList of Object Sort Example(Comparable and Comparator) | Java Hungry
@Override public int compareTo(Student comparestu) { int compareage=((Student)comparestu).getStudentage(); /* For Ascending order*/ return this.studentage-compareage; /* For Descending order do like this */ //return compareage-this.studentage; } @Override public String toString() { return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]"; } } Now we can call Collections.sort() on ArrayList · import java.util.*; public class ArrayListSort { public static void main(String args[]) { ArrayList<Student> arraylist = new ArrayList<Student>(); arraylist.add(new Student(222, "Messi", 29)); arraylist.add(new Student(333, "Ronaldo", 31)); arraylist.add(new Student(111, "john", 23)); Collections.sort(arraylist); for(Student str: arraylist){ System.out.println(str); } } } Output
🌐
Oreate AI
oreateai.com › blog › unlocking-custom-sorting-a-deep-dive-into-java-arraylist-comparators › e566c28edd2b18578975e6bc925d8cf3
Unlocking Custom Sorting: A Deep Dive Into Java ArrayList Comparators - Oreate AI Blog
January 27, 2026 - It empowers you to dictate the exact order of elements in your list, transforming a generic collection into a precisely organized dataset tailored to your application's unique requirements.
🌐
GeeksforGeeks
geeksforgeeks.org › java › sort-arraylist-in-descending-order-using-comparator-in-java
Sort ArrayList in Descending Order Using Comparator in Java - GeeksforGeeks
July 23, 2025 - If there is any need to reorder an ArrayList on the basis of the variable of string type like name, etc. rewrite the compare() function Like below. Ascending Order public int compare(Shop s1, Shop s2) { return s1.name.compareTo(s2.name); } ...