Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

java - TreeMap<Integer, Integer> remove not working

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public int compare(Integer a, Integer b) {
    if (base.get(a) >= base.get(b)) {
        return -1;
    } else {
        return 1;
    } // returning 0 would merge keys
}

This comparator is flawed as (quite apart from it being inconsistent with equals) it does not satisfy the comparator contract which states that compare(a,b) > 0 implies compare(b,a) < 0 and vice versa. And since TreeMap relies on the comparator returning 0 to find the key you're trying to remove() it will never be able to remove anything - no matter what key you try and search for the map will never think that the key is present.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...