1

Imagine I have two POJO bean like:

public class Employee {
   private String name;
   private long id;
   ....
   //GETTERS AND SETTERS
}

public class Buildings {
   private String name;
   private long numOfEmployees;
   ...
   //GETTERS AND SETTERS
}   

now I made two list of these POJOs (empList & bldList)and I want to sort them using Collections.sort feature like this :

Collections.sort(empList , new Comparator<Employee>() {
       public int compare(Employee o1, Employee o2) {
         return o2.getId().compareTo(o1.getId());
       }
});

and another sorting like this :

Collections.sort(bldList, new Comparator<Buildings>() {
       public int compare(Buildings o1, Buildings o2) {
         return o2.getNumOfEmployees().compareTo(o1.getNumOfEmployees());
       }
});

now instead of writing comparator twice for this I was thinking that I find a solution that I can use generics and do this operation inside the method, what came to my mind was a method similar to this:

public <T> List<T> sortMyList(List<T> list){
   Collections.sort(list, new Comparator<T>() {
         public int compare(T o1, T o2) {
            // I don't know how to call the Building and Employee methods here so I just show it with "???"
            return o1.???.compareTo(o2.???);
          }
   });
}

How can I make this method to work well for me ?

Mehdi
  • 3,408
  • 3
  • 30
  • 59
  • 1
    Have your classes implement `Comparable` instead. http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List) also see: http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html – Brian Roach Jan 08 '14 at 07:43
  • possible duplicate of [How to sort an array of objects in Java?](http://stackoverflow.com/questions/18895915/how-to-sort-an-array-of-objects-in-java) – Brian Roach Jan 08 '14 at 07:47

4 Answers4

5

Make your classes implement Comparable<T>.

class Employee implements Comparable<Employee>{

   //override compareTo()

}

Similarly for Buildings

Then use Collections.sort(listOfEmployee);

Narendra Pathai
  • 38,384
  • 18
  • 73
  • 117
1

You can have your POJOs implement the Comparable interface

Itay Karo
  • 16,882
  • 3
  • 36
  • 56
0

It is general consensus that to implement Comparable is the correct and best way to go.

My answer is a "can it be done" rather than "best practice" of "How can I make this method to work well for me ?"

This answer should be seen as academic (and in need of improvement at that) and not as an implementable solution.

public <T> void sortMyList(List<T> list) {

    Collections.sort(list, new Comparator<T>() {
        Method theMethod = null;

        @Override
        public int compare(T o1, T o2) {
            if (theMethod == null) {
                Method[] methods = o1.getClass().getMethods(); //reflection
                for (Method m : methods) {
                    if ("long".equals(m.getReturnType().toString())) {
                        theMethod = m;
                        break;
                    }
                }
            }
            try {
                return ((Long) (theMethod.invoke(o1, null))).compareTo((Long) (theMethod.invoke(o2, null)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        }
    });
}

This assumes that the first method, returning a long, found in the list is used to compare.

The loop to get the Method is in the compare(T o1, T o2) to avoid problems like getting the class of a generic type

Community
  • 1
  • 1
ufis
  • 176
  • 10
-1

Another solution (than using comparable)

You can use instanceof operator in java .

Example :

public <T> List<T> sortMyList(List<T> list){
           Collections.sort(list, new Comparator<T>() {
           public int compare(T o1, T o2) {
                if(o1 instanceof Employee && o2 instanceof Employee)
                    return o2.getId().compareTo(o1.getId());
                else if(o1 instanceof Buildings && o2 instanceof Buildings)
                      return o2.getNumOfEmployees().compareTo(o1.getNumOfEmployees());
           }
  });
} 
Sujith PS
  • 4,447
  • 3
  • 29
  • 59
  • 1
    I would not recommend this, using instanceof in this manner is terrible code style. Especially since this is solved elegantly with an interface. – Others Jan 08 '14 at 07:48
  • Yes I understood , But if Employee and Buildings classes are not changeable , then ? – Sujith PS Jan 08 '14 at 07:51
  • 1
    he said he wrote them, why would they not be changeable? – Others Jan 08 '14 at 07:54