我试图通过执行以下循环来获取TreeMap的前10个元素:
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);
该打印outVal is 11377,11377,11377,11377,11377,11377,11377,11377,11377,11377 Integer工具Comparable,为什么可能remove不起作用?
outVal is 11377,11377,11377,11377,11377,11377,11377,11377,11377,11377
Integer
Comparable
remove
更新 这是我的sortMap实现:
sortMap
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 } }
更新 这很有用:Java Map按值排序。
public int compare(Integer a, Integer b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } // returning 0 would merge keys }
此比较器有缺陷,因为(除与之不一致之外equals)它不满足表示compare(a,b) > 0暗示的比较器协定,compare(b,a) < 0反之亦然。而且由于TreeMap依赖于比较器返回0来查找您要尝试找到的密钥,remove()所以它将永远无法删除任何内容- 无论您尝试使用哪种密钥并搜索映射,都永远不会认为该密钥存在。
equals
compare(a,b) > 0
compare(b,a) < 0
TreeMap
remove()