I'm trying to get the top 10 elements of a TreeMap by executing this loop:
TreeMap<Integer, Integer> sortedMap = sortMap(m);
String outString = "";
int count = 10;
while (count > 0) {
count--;
Integer k = sortedMap.firstKey();
outString += String.valueOf(k);
sortedMap.remove(k);
if (count != 0) {
outString += ",";
}
}
System.out.println("outVal is " + outVal);
This prints outVal is 11377,11377,11377,11377,11377,11377,11377,11377,11377,11377
Integer
implements Comparable
, so why might remove
not be working?
UPDATE Here's my sortMap
implementation:
public static TreeMap<Integer, Integer> sortMap(HashMap<Integer, Integer> map) {
ValueComparator bvc = new ValueComparator(map);
TreeMap<Integer,Integer> sorted_map = new TreeMap<Integer,Integer>(bvc);
sorted_map.putAll(map);
return sorted_map;
}
class ValueComparator implements Comparator<Integer> {
java.util.Map<Integer, Integer> base;
public ValueComparator(java.util.Map<Integer, Integer> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(Integer a, Integer b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
UPDATE This was helpful: Java Map sort by value.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…