Creating an universal comparator to sort a tree map problem
-
20-09-2019 - |
Question
This is where I'm at:
public final Comparator<Object> ID_IGN_CASE_COMP = new Comparator<Object>() {
public int compare(Object o1, Object o2) {
String s1 = null;
String s2 = null;
try {
Class c = o1.getClass();
IO.println(c.getName()); //java.lang.string instead of Animal
Method method = c.getMethod("getId");
s1 = (String)method.invoke(o1);
s2 = (String)method.invoke(o2);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {}
return s1.compareToIgnoreCase(s2);
}
};
private Map< String, Animal> _animals = new TreeMap< String, Animal>(ID_IGN_CASE_COMP);
I'm getting java.lang.string
instead of Animal
class. Any idea on how can I solve this issue?
Solution
The TreeMap is ordered in terms of its keys. The keys of your map are Strings. What problem are you actually solving?
OTHER TIPS
The Map is based on the ordering of the keys (not values), so that explains why you've got a String instead of an Animal.
You are almost there, If you use a TreeSet instead of a TreeMap, you can use your comparator on one of the fields of the Animal class.
Btw, you are using reflection to get to the Id field, if the Animal
baseclass contains the .getId()
method, you can cast and call the method without reflection.
If you want to sort a Map
by value, and the current String
key is actually a property of Animal
, then best way is probably to create a LinkedHashMap
based on a SortedSet<Animal>
or maybe a List<Animal>
which is sorted using Collections#sort()
.
Set<Animal> animalSet = createAndSortItSomehow();
Map<String, Animal> animalMap = new LinkedHashMap<String, Animal>();
for (Animal animal : animalSet) {
animalMap.put(animal.getSomeStringYouWantAsKey(), animal);
}
Only pitfall is that you have to re-sort if whenever you want to add a new Animal
to the map.