compare and sort different type of objects using java Collections

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

Answers


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 :


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

Need Your Help

XWPF - remove cell text

java apache-poi xwpf

I have a .docx file that contains a single table. I want to remove all text from rows 2 to the end.

Generic parameter 'Element' could not be inferred Swift closure

ios swift closures swift3

I'm trying to return an array of Strings in a Swift 3 closure. I'm getting the error Generic parameter 'Element' could not be inferred when I try to return the array. Here's the relevant code: