Sort ArrayList of custom Objects by property

Posted by Samuel on Stack Overflow See other posts from Stack Overflow or by Samuel
Published on 2010-05-06T21:09:36Z Indexed on 2010/05/06 21:28 UTC
Read the original article Hit count: 409

Filed under:
|
|

Hello World!! :D

I had a question which is pretty easy if you know the answer I guess. I read about sorting ArrayLists using a Comparator but somehow in all of the examples people used compareTo which according to some research is a method working on 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);
    ...
}

I just started with Java so please forgive my ignorance :)

Thanks in advance!!

-Samuel

© Stack Overflow or respective owner

Related posts about java

Related posts about comparator