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)
We generally use Collections.sort() method to sort a simple array list. However if the ArrayList is of custom object type then in such case you have two options for sorting- comparable and comparator interfaces.
Discussions

[Java] How to sort an arraylist of Objects, based on Objects String field?
You mentioned both components that you needed: You need to implement Comparable, which it looks like you've done (although with a strange second line that's kinda redundant) You then just call Collections.sort(myList) where myList is some sort of List Alternatively, you can create a Comparator (this is a separate class you'll have to define, and then instantiate an instance of it) and then call Collections.sort(myList, myComparator) More on reddit.com
🌐 r/learnprogramming
2
1
April 27, 2022
java - How to sort Objects in an Arraylist with an Object parameter - Stack Overflow
In CompareObj class, how can I use the implemented method compare(s1,s2), how can I use this method to sort my arraylist of student objects? ... Have you looked at the JavaDoc for the Collections class? More on stackoverflow.com
🌐 stackoverflow.com
Sorting an ArrayList of objects by their attribute of type double in Java/OOP
I tried to use Arrays.sort for the first time but I'm not really getting anywhere. What does "not really getting anywhere" mean? What specifically did you try, and what didn't work? You'll need to create a custom Comparator object and pass it to sort in order to define what order the values should be sorted in. More on reddit.com
🌐 r/learnprogramming
6
4
October 9, 2022
Sort Java ArrayList based on an object's attribute​
I may be understanding the question wrong, but if you are using Collections.sort() just make a new Comparator. More on reddit.com
🌐 r/learnprogramming
2
5
December 29, 2018
🌐
W3Schools
w3schools.com › java › java_advanced_sorting.asp
Java Advanced Sorting (Comparator and Comparable)
Sort lists of Java objects with Comparable and Comparator to control the ordering.
🌐
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 - ArrayList is a part of the collection framework and is present in java.util package. ... Takes two objects from the list o1 and o2. Compares the two object's customProperty using compareTo() method. And finally returns a positive number if o1's property is greater than o2's, negative if o1's property is lesser than o2's, and zero if they are equal. Based on this, the list is sorted based on the least property to the greatest and stored back on to list.
🌐
Reddit
reddit.com › r/learnprogramming › [java] how to sort an arraylist of objects, based on objects string field?
r/learnprogramming on Reddit: [Java] How to sort an arraylist of Objects, based on Objects String field?
April 27, 2022 -

How do i alphabetically sort an arraylist of objects, based on the objects field "name". I have object Car, with a compareTo method:

  @Override
  public int compareTo(Car cName) {
 
    int last = this.carName.compareTo(cName.carName);

    return last == 0 ? this.carName.compareTo(cName.carName) : last;

  }

In a separate class there is an array list that captures all of these Car Objects. I need to sort that list alphabetically, then print out the table of Car Objects in alphabetical order. Im stuck trying to implement the above into the sort for the arraylist that i will iteratively print over.

I have looked at Collections.sort() but i don't want to edit the class name to implement comparator.

 public void printRacers() {
    // get
    //
    ArrayList<Car> carNames = new ArrayList<>();
    carNames.addAll(racers);
    
    System.out.println("Car name    Race    Car  number");
    for (int i = 0; i < carNames.size(); i++) {
      Car c = carNames.get(i);
      
      String cName = c.getCarName();
      String cRace = d.getRaceName();
      int sNum = c.getCarNumber();

      String outputString = cName + "   " + cClass + "   " + sNum;
      System.out.println(outputString);

    }

Im really stuck on this and would appreciate anyone's help!

Thanks

🌐
GitHub
gist.github.com › SheldonWangRJT › cdd2c1d0bfe092dea30a3e929aba325f
How to sort a List<Object> in JAVA in the best way? · GitHub
High order functions with lambda is very easy in Swift (see article Here) but not that easy in languages like Objective-C or C++. In JAVA we can do it but since JAVA has too many versions, there are a lot different ways to do it, and there is always a better one you can choose. Assuming we have a class like: class Student { private int age; private String name; public Student(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } } And we will have an list of Student to sort: List<Student> list = new ArrayList<Student>(); list.add(new Student(33, "A")); list.add(new Student(11, "C")); list.add(new Student(22, "B")); Comparator is the most classic one but also the one with the longest typing, basically we need to create a new Comparator for our sorting.
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java dates › sorting objects in a list by date
Sorting Objects in a List by Date | Baeldung
April 3, 2025 - This interface lets us define a strategy for comparing objects with other objects of the same type. This is used to sort the objects in their natural ordering form or defined by the compareTo() method. In Java, natural order refers to how we should sort primitives or objects in an array or collection.
🌐
Medium
medium.com › @AlexanderObregon › sorting-lists-in-java-using-collections-sort-14b150ac8682
Sorting Lists in Java Using Collections.sort | Medium
June 4, 2025 - For ArrayList, it runs the TimSort algorithm. TimSort combines two sorting techniques: merge sort and insertion sort. It checks whether parts of the list are already in order and uses that to avoid extra comparisons.
🌐
Spring Framework Guru
springframework.guru › home › sorting arraylists in java: a practical guide
Sorting ArrayLists in Java: A Practical Guide - Spring Framework Guru
October 22, 2024 - Since ArrayList is part of the Java Collections Framework, we can use the Collections.sort() method. This works nicely on Wrapped Primitives (String, Integer, Long, etc), or objects which implement the Comparable interface.
🌐
Baeldung
baeldung.com › home › java › java collections › sort collection of objects by multiple fields in java
Sort Collection of Objects by Multiple Fields in Java | Baeldung
January 8, 2024 - Since Java 8, there are several static methods added to the Comparator interface that can take lambda expressions to create a Comparator object.
🌐
Programiz
programiz.com › java-programming › examples › sort-custom-objects-property
Java Program to Sort ArrayList of Custom Objects By Property
Created with over a decade of experience and thousands of feedback. ... import java.util.*; public class CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; } public static void main(String[] args) { ArrayList<Customobject> list = new ArrayList<>(); list.add(new CustomObject("Z")); list.add(new CustomObject("A")); list.add(new CustomObject("B")); list.add(new CustomObject("X")); list.add(new CustomObject("Aa")); list.sort((o1, o2) -> o1.getCustomProperty().compareTo(o2.getCustomProperty())); for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } }
🌐
BezKoder
bezkoder.com › home › java – sort arraylist of objects
Java - Sort ArrayList of Objects - BezKoder
December 27, 2019 - The examples show you how to return new sorted ArrayList using sorted() method of Stream interface in Java 8.
🌐
Reddit
reddit.com › r/learnprogramming › sorting an arraylist of objects by their attribute of type double in java/oop
r/learnprogramming on Reddit: Sorting an ArrayList of objects by their attribute of type double in Java/OOP
October 9, 2022 -

How's it going everyone?

I need some help in this. So I have this method below that works fine and basically prints the toString representation of different employees by going through each one in the Arraylist of employees objects called Company. Employees are objects with the following attributes: ID, name and gross salary. Now I have to create another method that does the same thing pretty much, but this time prints the toString of my employees by ascending order sorted by the gross salary of employees which is a method I have called getEmployeeGrossSalary() because i'm using encapsulation. I tried to use Arrays.sort for the first time but I'm not really getting anywhere. Anyone could give some hints or has a simple plan for me to implement this?

N.B: My method to create has to return a String which is the toStrings of the employees in my Company ArrayList otherwise I would have problems in the testings my professor made.

Always appreciative of your help <3

//From my company class

public String printAllEmployees(){

        StringBuilder printEmployees = new StringBuilder();

        for (Employee employee : Company){
            printEmployees.append(employee.toString()).append("\n");

        } return "All registered employees: \n" + printEmployees;
    }

//From my employee class

public String toString() {
            String grossSalaryTruncated = 
String.format("%.2f",this.getEmployeeGrossSalary());
            return this.getEmployeeName() + "'s gross salary is " + grossSalaryTruncated + " USD per month.";
        }

Ended up with this (below) and it worked somehow xD. Can someone just explain how it is working? I'm not really familiar with the syntax..

public String printSortedEmployees() {

    StringBuilder printSortedEmps = new StringBuilder();

    Company.sort(Comparator.comparingDouble(Employee::getEmployeeGrossSalary));
    for (Employee employee : Company) {
        printSortedEmps.append(employee.toString()).append("\n");

    }
    return "Employees sorted by gross salary (ascending order): \n" + printSortedEmps;
}
🌐
Medium
kevalpadsumbiya.medium.com › custom-sorting-of-list-of-objects-using-java-stream-b24d93e6e71e
Custom sorting of list of objects using Java Stream | Medium
February 13, 2023 - package com.custom.sorting.service; import com.custom.sorting.model.Seller; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class CustomSorting { public static void main(String[] args) { List<Seller> sellerList = getSampleListOfSellers(); //seller name comparator Comparator<Seller> sellerNameComparator = Comparator.comparing(Seller::getSellerName); //seller location distance comparator Comparator<Seller> sellerLocationDistanceComparator = Comparator.comparing(Seller::getDistanceFromMyLocation); //seller state comparator Co
🌐
W3Schools
w3schools.com › java › java_sort_list.asp
Java Sort a List - List Sorting
Sort a Java list alphabetically or numerically with Collections.sort().
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-sort-arraylist-of-custom-objects-by-property
Java Program to Sort ArrayList of Custom Objects By Property - GeeksforGeeks
July 23, 2025 - // Java Program to Sort ArrayList ... sortList(int length) { // Sorting the list using lambda function list.sort( (a, b) -> a.getValue().compareTo(b.getValue())); System.out.println("Sorted List : "); // Printing the sorted List ...
🌐
Reddit
reddit.com › r/learnprogramming › sort java arraylist based on an object's attribute​
r/learnprogramming on Reddit: Sort Java ArrayList based on an object's attribute​
December 29, 2018 -

I'm trying to sort an ArrayList in alphabetical order, based on an attribute of the objects the ArrayList contains. For example: I have an object that represents a product and I want to sort the products based on the suppliers name of the attribute. This attribute is a string and could be something like "Old Navy", "Gap", "Peebles", etc.

Is it possible to do a lambda and sort based on product.supplierName? I was thinking of just putting everything into a HashMap with the key being the suppliers name, and then looping over the keys and appending each keys value to an ArrayList, but this doesn't seem like the most efficient method.

🌐
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
For example, You can sort an ArrayList of Objects in descending order by just reversing the order of your Comparator. The JDK API provides another convenient method Collections.reverseOrder(Comparator c) which returns a comparator with the opposite order of the given Comparator. Btw, this is not the only way to sort an ArrayList of objects in Java.
🌐
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 - This snippet creates an ArrayList of Employee objects and sorts them using the Comparable interface implementation. 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. ... import java.util.Comparator; public class IdComparator implements Comparator<Employee> { @Override public int compare(Employee e1, Employee e2) { return Integer.compare(e1.getId(), e2.getId()); } } Explain Code