Use a custom comparator:

Collections.sort(nodeList, new Comparator<DataNode>(){
     public int compare(DataNode o1, DataNode o2){
         if(o1.degree == o2.degree)
             return 0;
         return o1.degree < o2.degree ? -1 : 1;
     }
});
Answer from Mark Elliot on Stack Overflow
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-arraylist-of-object-sort-example-comparable-and-comparator
Java ArrayList of Object Sort Example (Comparable And Comparator)
And I want to have an ArrayList of Student Object, which can be defined like this: import java.util.*; public class ArrayListSorting { public static void main(String args[]){ ArrayList<Student> arraylist = new ArrayList<Student>(); arraylist.add(new Student(223, "Chaitanya", 26)); arraylist.add(new Student(245, "Rahul", 24)); arraylist.add(new Student(209, "Ajeet", 32)); Collections.sort(arraylist); for(Student str: arraylist){ System.out.println(str); } } }
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 - Sort ArrayList of custom Objects by property - Stack Overflow
I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings. I wanted to sort an ArrayList of custom More on stackoverflow.com
🌐 stackoverflow.com
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
java - Sorting an ArrayList by the value of a field in the objects it stores - Stack Overflow
Possible Duplicate: Sorting ArrayList of Objects by Object attribute Basically I have an ArrayList that stores objects, each of those objects has a field that stores an integer. I want to store... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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
In order to sort an ArrayList of custom or user-defined objects, you need two things, first a class to provide ordering and a method to provide sorting. If you know about ordering and sorting in Java then you know that the Comparable and Comparator ...
🌐
BezKoder
bezkoder.com › home › java – sort arraylist of objects
Java - Sort ArrayList of Objects - BezKoder
December 27, 2019 - You will know how to: sort ArrayList of Objects by one field or multiple fields use custom Comparator to sort ArrayList of Objects implement Comparable interface to sort ArrayList of Objects conveniently Java ArrayList […]
🌐
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

🌐
How to do in Java
howtodoinjava.com › home › java sorting › java collections sort()
Java Collections sort() - HowToDoInJava
December 14, 2022 - For example, the domain object Employee has default sorting on the name field. Checkout for comparison logic in compareTo() method. public class Employee implements Comparable<Employee>{ private Integer id; private String name; private String email; private LocalDate dateOfBirth; //Getters and Setters @Override public int compareTo(Employee e) { return this.getName().compareTo(e.getName()); } } Nest Java program sorts the list of Employee objects by their name; ArrayList<Employee> employees = methodReturnsUnsortedList(); //Narutal order sorting Collections.sort(employees); //Reverse sorting Collections.sort(employees, Collections.reverseOrder()); The second parameter in sort() method takes an instance of Comparator.
🌐
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.
Find elsewhere
🌐
Dirask
dirask.com › posts › Java-sort-ArrayList-based-on-Object-field-przXBp
Java - sort ArrayList based on Object field
... users.sort(new Comparator<User>() { public int compare(User u1, User u2) { if (u1.getAge() == u2.getAge()) return 0; return u1.getAge() < u2.getAge() ? -1 : 1; } }); In this example, we create a custom Comparator that will help us to sort ...
🌐
Programiz
programiz.com › java-programming › examples › sort-custom-objects-property
Java Program to Sort ArrayList of Custom Objects By Property
Note: For int, we use Comparator.comparingInt(CustomObject::getCustomProperty) for sorting the ArrayList based on the int property.
🌐
Vultr
docs.vultr.com › java › standard library › java › util › arraylist › sort()
Java ArrayList sort() - Order Elements
November 15, 2024 - Create a comparator that defines a custom sort order based on one of the fields. Sort an ArrayList of these objects using the custom comparator. ... import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class ...
🌐
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 - So we pass User::getCreatedOn to ... we didn’t want to modify the original list, but return a new sorted list. In this situation, we can use the sorted() method from the Stream interface introduced in Java 8....
🌐
DZone
dzone.com › data engineering › data › different approaches to sorting elements of an arraylist in java
Java ArrayList: Approaches to Sorting Elements
November 1, 2015 - The class whose object you want to sort must implement Comparable and override the compareTo() method. This essentially means you would only be able to compare the objects based on one field (which was age in our example).
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) {
        ...
    }
});
🌐
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.

🌐
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
🌐
Javatpoint
javatpoint.com › how-to-sort-arraylist-in-java
How to Sort ArrayList in Java - javatpoint
How to Sort ArrayList in Java with java tutorial, features, history, variables, object, class, programs, operators, for-loop, oops concept, inheritance, array, string, map, math, methods, examples etc.
🌐
YouTube
youtube.com › watch
Sort ArrayList of Objects - YouTube
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
Published: March 18, 2016
🌐
Stack Overflow
stackoverflow.com › questions › 13550977
java - Sorting an ArrayList by the value of a field in the objects it stores - Stack Overflow
Create your custom comparator class implementing java.util.Comparator and use java.util.Collections.sort(list, comparator).
🌐
Quora
quora.com › How-do-I-sort-an-ArrayList-of-objects-by-each-objects-integer-parameter
How to sort an ArrayList of objects by each object's integer parameter - Quora
Answer (1 of 4): Well, Java provides a very good API to sort a list of objects, You can implement a Comparator and pass that comparator to Collections.sort along with the list you wanted to sort. Let’s understand what is being done behind the scenes, [code]public class Employee { private int a...
🌐
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 - We’ll be comparing Person objects first based on name and then on age throughout our examples: public class Person { @Nonnull private String name; private int age; // constructor // getters and setters } Here, we’ve added a @Nonnull annotation to keep the examples simple. But in production code, we may need to handle the comparison of nullable fields. Java provides the Comparator interface for comparing two objects of the same type.