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
Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
By default, Collection. sort performs the sorting in ascending order. If we want to sort the elements in reverse order we could use following methods: reverseOrder() : Returns a Comparator that imposes the reverse of natural ordering of elements of the collection.
The compareTo method defines the natural order; the default way for ordering objects of a class. It should return a negative integer(usually -1), if the current triggering object is less than the passed one, and positive integer (usually +1) if greater than, and 0 if equal.
For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.
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 :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With