Create a comparator class to handle sorting:

private class MyObjectComparator<MyObject> implements Comparator<MyObject> {

  /**
   * {@inheritDoc}
   */
  @Override
  public int compare(MyObject o1, MyObject o2) {
     return o2.getSequenceNumber() - o1.getSequenceNumber();
  }

}

Then sort your ArrayList with it:

Collections.sort(myArrayList, new MyObjectComparator());
Answer from Adam on Stack Overflow
๐ŸŒ
Techie Delight
techiedelight.com โ€บ home โ€บ java โ€บ sort a list of objects using comparable in java
Sort a list of objects using Comparable in Java | Techie Delight
November 11, 2025 - Therefore, if an object implements ... Objects that implement this interface can also be used as keys in a sorted map (TreeMap) or as elements in a sorted set (TreeSet), without the need to specify a comparator...
๐ŸŒ
Amir Boroumand
steelcityamir.com โ€บ blog โ€บ sort-list-of-objects-by-field-java
Sort a List of Objects by Field in Java ยท Amir Boroumand | Software engineer based in Pittsburgh, PA
May 9, 2018 - Weโ€™ll use the following User ... different approaches and explore the benefits and limitations of each. We can use the Comparable interface to define the default sort criteria for a class....
๐ŸŒ
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 - The sorting logic can sometimes become difficult to implement if we want to sort the objects on multiple fields. In this tutorial, weโ€™ll discuss several different approaches to the problem, along with their pros and cons. Letโ€™s define a Person class with two fields, name and age. Weโ€™ll be comparing Person objects first based on name and then on age throughout our examples:
๐ŸŒ
GitHub
gist.github.com โ€บ SheldonWangRJT โ€บ cdd2c1d0bfe092dea30a3e929aba325f
How to sort a List<Object> in JAVA in the best way?
Lambda is a better and more concise way to replace Comparator for developers. (Similar in Swift) //lambda list.sort((Student o1, Student o2)->o1.getName().compareTo(o2.getName())); //lambda list.sort((o1, o2)->o1.getAge().compareTo(o2.getAge()));
๐ŸŒ
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

Find elsewhere
Top answer
1 of 16
1736

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) {
        ...
    }
});
๐ŸŒ
Quora
quora.com โ€บ How-do-I-perform-a-custom-sort-on-List-Set-and-Map-in-Java
How to perform a custom sort on List, Set and Map in Java - Quora
Answer: First we should understand a difference between Comparable and Comparator interface. or when to use comparable and comparator interface? Comparable interface is defined in java.lang package Comparator is defined in java.util package Used for Single sorting sequence Used for multiple sor...
๐ŸŒ
JavaTechOnline
javatechonline.com โ€บ home โ€บ how to sort the list in java 8
How To Sort The List In Java 8 - JavaTechOnline
July 14, 2025 - The below example demonstrates the concept of How to sort the List in Java 8 using Method Reference. By using an instance method reference and the Comparator.comparing method, we can also avoid defining even the comparison logic itself.
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ sorting-lists-in-java-using-collections-sort-14b150ac8682
Sorting Lists in Java Using Collections.sort | Medium
June 4, 2025 - Learn how Javaโ€™s Collections.sort works behind the scenes, including ascending and descending order, comparator logic, null handling, and TimSort mechanics.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 382108 โ€บ java โ€บ Sorting-List-objects-field
Sorting a List of objects by field (Java in General forum at Coderanch)
Then call either java.util.Arrays.sort() (if you have an array) or java.util.Collections.sort() (if you have an actual List) to sort the items, passing an instance of your Comparator class as an argument. ... You can try using org.apache.commons.beanutils.BeanComparator.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-sort-list
How to Sort a List in Java | DigitalOcean
August 3, 2022 - Sometimes we have to sort a list in Java before processing its elements. In this tutorial, we will learn how to sort a list in the natural order. We will also learn how to use our own Comparator implementation to sort a list of objects. Java List is similar to arrays except that the length of the list is dynamic and it comes in Java Collection framework.
๐ŸŒ
DZone
dzone.com โ€บ data engineering โ€บ data โ€บ how to sort objects in java
How To Sort Objects In Java
February 27, 2018 - So far students sorting was done based on the Student's "name" not by "no". If we want to sort by "no", we just need to change the implementation of compareTo(Object o) of Student class and the implementation will look like:
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_sort_list.asp
Java Sort a List - List Sorting
Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically.
Top answer
1 of 6
76

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
    public int compare(GraduationCeremony o1, GraduationCeremony o2) {
        int value1 = o1.campus.compareTo(o2.campus);
        if (value1 == 0) {
            int value2 = o1.faculty.compareTo(o2.faculty);
            if (value2 == 0) {
                return o1.building.compareTo(o2.building);
            } else {
                return value2;
            }
        }
        return value1;
    }
}

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

2 of 6
43

Yes, you absolutely can do this. For example:

public class PersonComparator implements Comparator<Person>
{
    public int compare(Person p1, Person p2)
    {
        // Assume no nulls, and simple ordinal comparisons

        // First by campus - stop if this gives a result.
        int campusResult = p1.getCampus().compareTo(p2.getCampus());
        if (campusResult != 0)
        {
            return campusResult;
        }

        // Next by faculty
        int facultyResult = p1.getFaculty().compareTo(p2.getFaculty());
        if (facultyResult != 0)
        {
            return facultyResult;
        }

        // Finally by building
        return p1.getBuilding().compareTo(p2.getBuilding());
    }
}

Basically you're saying, "If I can tell which one comes first just by looking at the campus (before they come from different campuses, and the campus is the most important field) then I'll just return that result. Otherwise, I'll continue on to compare faculties. Again, stop if that's enough to tell them apart. Otherwise, (if the campus and faculty are the same for both people) just use the result of comparing them by building."

๐ŸŒ
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.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-sort-a-list-in-java
How to Sort a List in Java โ€“ Java List Sorting Example
January 24, 2023 - We call this process sorting. Sorting refers to arranging data in a specific order using certain criteria. You can sort different types of data, including numbers, strings, and objects. Java provides built-in methods for sorting, such as the Collections classes.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_arraylist_sort.asp
Java ArrayList sort() Method
Non-primitive types must implement Java's Comparable interface in order to be sorted without a comparator.