我正在尝试通过执行以下循环来获取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不能正常工作?

更新这是我的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 sort by value

最佳答案

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()的密钥,因此它将永远无法删除任何内容-无论您尝试使用哪种密钥并搜索地图,都永远不会认为该密钥是当下。

关于java - TreeMap <Integer,Integer>删除不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21119011/

10-13 02:00