Use Collections.sort(List<T> list, Comparator<? super T> c)
and pass a custom comparator for your DAO objects.
It's by far easier if all of your list items share a common supertype that provides a method to get the item rank. Assuming you have such an interface, let's call it RankProvider
, the comparator could look like:
public class Comparator<RankProvider> {
@Override
public int compare(RankProvider o1, RankProvider o2) {
return o1.getItemRank().compareTo(o2.getItemRank());
}
}
Pass an instance of this comparator or define an anonymous class.
Note - the example give above assumes, that the item rank is either a java primitive (like int
) or a String or, in other words, is a Comparable
(directly or after inboxing)
If you don't have a common superclass or interface, then comparing is less trivial. You'll either have to know all possible types and handle them each by each or you know that all types have the same method (name) and you can reflect the rank. One example for a comparator that compares known but random types:
public class Comparator { // no generics this time
@Override
public int compare(Object o1, Object o2) {
Object[] comparables = new Object{o1, o2};
int[] ranks = new int[2];
for (int i = 0; i < 2; i++) {
if (comparables[i] instanceof MyType1) {
ranks[i] = ((MyType1) comparables[i]).getRank(); // rank getter for MyType1 type
continue;
}
if (comparables[i] instanceof MyType2) {
ranks[i] = ((MyType2) comparables[i]).getRank(); // rank getter for MyType2 type
continue;
}
// ...
}
return ranks[0] - ranks[1]; // ascending order
}
}
This could be done if you have no chance to refactor your DAOs to implement a shared interface.