Adam Lyu
Adam Lyu

Reputation: 461

why different key with duplicated value disappear when transfer hashmap to treemap

I use the code below to sort my hashmap by its value. But the result seems confused because it only keep one entry for one value and remove another entry with duplicate value. Here is the Comparator code:

class ValueComparator implements Comparator {
    Map map;

    public ValueComparator(Map map) {
        this.map = map;
    }

    public int compare(Object keyA, Object keyB) {
        Comparable valueA = (Comparable) map.get(keyA);
        Comparable valueB = (Comparable) map.get(keyB);
        return valueB.compareTo(valueA);
    }

And here is how I use it:

 TreeMap sortedMap=new TreeMap(new ValueComparator(allCandidateMap));
        sortedMap.putAll(allCandidateMap);

Upvotes: 0

Views: 141

Answers (1)

Alex Hall
Alex Hall

Reputation: 36043

That makes perfect sense. You've declared that if two keys map to equal values in allCandidateMap, they should be considered equal, since your compare will be returning 0.

What this comes down to is that your comparator has almost reversed the roles of key and value. If you try doing other operations you will probably find that the values of the map often behave like keys. Methods like get and containsKey will act as if they're looking up the values, not the keys (but then get will return the value you passed in, so values are still values as well). The comparator defines the behaviour of the TreeMap, and you've asked for very weird behaviour.

Upvotes: 1

Related Questions