This has been asked several times, i know, but help me understand something.
You have a map you need sorted by Value
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("a", 1);
m.put("b", 13);
m.put("c", 22);
m.put("d", 2);
You call a method to make it happen
public static List<String> sortByValue(final Map<String, Integer> unsortedMap) {
List<String> sortedKeys = new ArrayList<String>();
sortedKeys.addAll(unsortedMap.keySet());
Collections.sort(sortedKeys, new MapComparator(unsortedMap));
return sortedKeys;
}
You have a comparator class
public MapComparator(Map<String, Integer> m) {
this.m = m;
}
@Override
public int compare(String a, String b) {
int x = m.get(a);
int y = m.get(b);
if (x > y)
return x;
if (y > x)
return y;
return 0;
}
This code, obviously is flawed. Please help me understand why?
You should be returning
1ifx > yand-1ify > x. TheComparatorcontract specifies that you return a negative number if the first value is less than the second, a positive number if the first is greater than the second, and zero if they’re equal.(Mind you, as it stands, this
Comparatorimplementation will break in very confusing ways if you ever happen to use values that aren’t in the original map.)Better yet, just return
Integer.compare(x, y), which does all that for you. (Only in Java 7, though.)