Home > DeveloperSection > Forums > Sort ArrayList of custom Objects by property
Mikki Halpin
Mikki Halpin

Total Post:23

Points:161
Posted on    July-10-2015 1:00 AM

 Java Java  Collection  Array List 
Ratings:


 1 Reply(s)
 463  View(s)
Rate this:
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 objects by one of their properties: a Date object (getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:
public class customComparator {
    public boolean compare(Object object1, Object object2) {
        return object1.getStartDate().before(object2.getStartDate());
    }
}
public class randomName {
    ...
    Collections.sort(Database.arrayList, new customComparator);
    ...
}


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    July-10-2015 8:09 AM

With Java 8 you can use a method reference for your comparator:
import static java.util.Comparator.comparing;
Collections.sort(list, comparing(MyObject::getStartDate));\

JAVA 8 lambda expression
Collections.sort(studList, (Student s1, Student s2) ->{
        return s1.getFirstName().compareToIgnoreCase(s2.getFirstName());
});

Don't want to miss updates? Please click the below button!

Follow MindStick