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
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.
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());
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 :