Search code examples
javahashmaptreemap

TreeMap Element does not removed


I created a map and then sort the values and put them in a TreeMap. But the problem is when I invoke the remove() method on Treemap, the element is not removed. Does anybody have any idea what the problem is?

Here is my code:

Map<String , Double> map=new HashMap<String, Double>();
TreeMap<String, Double> sortedItems = sortMap(map);
sortedItems.remove("I put the key here as a string");


  public TreeMap<String, Double> sortMap(Map<String, Double> map) {
        HashMap<String, Double> map2 = new HashMap<String, Double>(map);
        TreeMap<String, Double> sortedMap = SortByValue(map2);
        return sortedMap;
    }

public TreeMap<String, Double> SortByValue
        (HashMap<String, Double> map) {
    ValueComparator vc = new ValueComparator(map);
    TreeMap<String, Double> sortedMap = new TreeMap<String, Double>(vc);
    sortedMap.putAll(map);
    return sortedMap;
}
class ValueComparator implements Comparator<String> {

    Map<String, Double> map;

    public ValueComparator(Map<String, Double> base) {
        this.map = base;
    }

    public int compare(String a, String b) {
        if (map.get(a) >= map.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }

Solution

  • You need to return 0; when you expect a match. The way to solve this is to compare the key which it is otherwise a match. This way the same key will match, but only the same key.

    public int compare(String a, String b) {
        int cmp = -map.get(a).compareTo(map.get(b));
        if (cmp == 0)
            cmp = a.compareTo(b);
        return cmp;
    }
    

    This way String keys which map to the same Double are seen as different iff they are different Strings.