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);
...
}
You can use the Bean Comparator to sort on any property in your custom class.
Yes, you can. There are two options with comparing items, the Comparable interface, and the Comparator interface.
Both of these interfaces allow for different behavior. Comparable allows you to make the object act like you just described Strings (in fact, String implements Comparable). The second, Comparator, allows you to do what you are asking to do. You would do it like this:
That will cause the Collections.sort method to use your comparator for it's sorting mechanism. If the objects in the ArrayList implement comparable, you can instead do something like this:
The Collections class contains a number of these useful, common tools.
This code snippets might be useful. If you want to sort an Object in my case I want to sort by VolumeName:
This works. I use it in my jsp.
I prefer this process:
If you list of objects has a property called
startDate
, you call use this over and over. You can even chain themstartDate.time
.This requires your object to be
Comparable
which means you need acompareTo
,equals
, andhashCode
implementation.Yes, it could be faster... But now you don't have to make a new Comparator for each type of sort. If you can save on dev time and give up on runtime, you might go with this one.
Since technologies appear everyday, the answer will change in the time. I took a look at LambdaJ and seems very interesting.
You can try solving these tasks with LambdaJ. You can find it here: http://code.google.com/p/lambdaj/
Here you have an example:
Sort Iterative
Sort with lambda
Of course, having this kind of beauty impacts in the performance (an average of 2 times), but can you find a more readable code?