views:

82

answers:

3

Hi,

How to compare and sort different type of objects using java Collections .Below is the use case: For example DOG,MAN,TREE, COMPUTER,MACHINE - all these different objects has a common property say "int lifeTime". Now I want to order these obects based on the lifeTime property

Thx

+7  A: 

All of these objects should have a common abstract class/interface such as Alive with a method getLifeTime(), and you could have either Alive extends Comparable<Alive> or create your own Comparator<Alive>.

public abstract class Alive extends Comparable<Alive>{
    public abstract int getLifeTime();
    public int compareTo(Alive alive){
        return 0; // Or a negative number or a positive one based on the getLifeTime() method
    }
}

Or

public interface Alive {
    int getLifeTime();
}

public class AliveComparator implements Comparator<Alive>{
    public int compare(Alive alive1, Alive alive2){
        return 0; // Or a negative number or a positive one based on the getLifeTime() method
    }
}

After that the next step is to use either an automatically sorted collection (TreeSet<Alive>) or sort a List<Alive> with Collections.sort().


Resources :

Colin Hebert
If you implement `Alive.compareTo`, you should implement it properly, i.e. really compare the lifetimes of the two objects instead of returning 0. Otherwise you would need a (basically duplicate) implementation in every concrete subclass.
Péter Török
@Péter Török, I haven't done the implementation because I don't know the wanted order. And you don't really have to rewrite it in every subclass, this is the reason I used an abstract class in the first part and not an interface and also why I left this long comment on the `return 0` line.
Colin Hebert
Sorry, your code comment was not clear on this (to me at least); that's why I thought it better to add a clarifying comment :-)
Péter Török
+1  A: 

The easiest way would involve your classes all implementing an interface or extending a base class that expose the common attribute (lifeTime) used for the comparison. Otherwise, you could just create a Comparator that uses reflection to get the lifeTime attribute and use that value in the compare method for your comparator. Of course, this will throw exceptions if your collection ever contains an object that has no lifeTime attribute.

Jim Tough
+1  A: 

If all your classes implement a Living interface defined as it follows (always a good idea in Java):

public interface Living {
    int getLifeTime();
}

you can sort your collections of Living objects by using the lambdaj library as it follows:

List<Alive> sortedLivings = sort(livings, on(Alive.class).getLifeTime());
Mario Fusco
I knew this name sounded familiar. This question made me think that for now there is no solution to invert elements order in a given iterable (or to sort by the inverse of natural order/comparator) in lambdaj.
Colin Hebert