views:

554

answers:

7

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

+5  A: 

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:

Collections.sort(myArrayList, new MyComparator());

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:

Collections.sort(myArrayList);

The Collections class contains a number of these useful, common tools.

aperkins
+5  A: 

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 couple of smaller points which are not directly related to the question:

  1. By convention, classes start with an upper-case letter while methods and variables start with a lower-case letter. That's why I changed the name of the comparator to CustomComparator.
  2. Use the Javadocs. They will be invaluable if you keep working with Java.
Michael Myers
+1 for mentioning that it should return `int` and that you'd better to use `Date#compareTo()` for this. Why this isn't upvoted above the other answer is beyond me. This link may also be useful: [Object Ordering Tutorial at Sun.com](http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html).
BalusC
A: 

your customComparator class must implement java.util.Comparator in order to be used. it must also overide compare() AND equals()

compare() must answer the question: Is object 1 less than, equal to or greater than object 2?

full docs: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html

Vinny
A: 

You can use the Bean Comparator to sort on any property in your custom class.

camickr
A: 

Yes, that's possible for instance in this answer I sort by the property v of the class IndexValue

    // Sorting by property v using a custom comparator.
    Arrays.sort( array, new Comparator<IndexValue>(){
        public int compare( IndexValue a, IndexValue b ){
            return a.v - b.v;
        }
    });

If you notice here I'm creating a anonymous inner class ( which is the Java for closures ) and passing it directly to the sort method of the class Arrays

Your object may also implement Comparable ( that's what String and most of the core libraries in Java does ) but that would define the "natural sort order" of the class it self, and doesn't let you plug new ones.

OscarRyz
...but which you can just override with `Comparator` :)
BalusC
+1  A: 

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) {
        ...
    }
});
Björn
A: 

I prefer this process:

public class SortUtil
{    
    public static <T> List<T> sort(List<T> list, String sortByProperty)
    {
            Collections.sort(list, new BeanComparator(sortByProperty));
            return list;
    }
}

List<T> sortedList = SortUtil<T>.sort(unsortedList, "startDate");

If you list of objects has a property called startDate, you call use this over and over. You can even chain them startDate.time.

This requires your object to be Comparable which means you need a compareTo, equals, and hashCode 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.

Dustin Digmann
1, this answer was given 2 hours earlier with working code provided as well. There is no need to repost the same solution and clutter the forum especially since BeanComparator is not a standard class, so its not really a solution if the poster doesn't know what you are talking about. If you like the original suggestion you can upvote it and add a comment if you wish.
camickr