Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 767
JavaUser Avatar asked Oct 02 '10 12:10

JavaUser


People also ask

How the collection objects are sorted in Java?

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.

Which sorting is used in Collections sort in Java?

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.

Which method is used to compare two objects for sorting?

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.

How do you sort a list of objects based on an attribute of the objects in Java?

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.


1 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 :

  • Javadoc - Collections.sort()
  • Javadoc - Comparable
  • Javadoc - Comparator
like image 192
Colin Hebert Avatar answered Oct 16 '22 03:10

Colin Hebert