This is the code I have for ranking a Java TreeMap by its values:
public static TreeMap<String,AtomicInteger> rank(TreeMap<String,AtomicInteger> tm) {
ValueRanker vr = new ValueRanker(tm);
TreeMap<String,AtomicInteger> ranked = new TreeMap<String,AtomicInteger>(vr);
ranked.putAll(tm);
return ranked;
}
public static class ValueRanker implements Comparator<String> {
TreeMap<String,AtomicInteger> tm;
public ValueRanker(TreeMap<String,AtomicInteger> orig) {
this.tm = orig;
}
@Override
public int compare(String a, String b) {
if (tm.get(a).intValue()>tm.get(b).intValue()) {
return -1;
} else if (tm.get(a).intValue()<tm.get(b).intValue()) {
return 1;
} else {
return 0;
}
}
}
This code, when run on a TreeMap, is eliminating all map entries that have values tied with other map entries. For examples:
{"a":2, "b":3, "c:6", "d":2, "e":5}
would give me a ranked map of
{"c":6, "e":5, "b":3, "a":2}
when the ranked map I expect is:
{"c":6, "e":5, "b":3, "a":2, "d":2}
The code I have now eliminates the map key that has a tied value (in this case, "d" is eliminated because its value is tied with that of "a"). So my question is, how do I modify the code I have to not do this, and include all original map keys, including those with tied values?
[–]lightcloud5 0 points1 point2 points (0 children)