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 ?