Search code examples
javasortingdictionarycomparatortreemap

Comparator creates duplicates in TreeMap


I would like to sort my HashMap (or TreeMap) by values. I kind of achieved this by creating a custom Comparator that sorts after value. However whenever I put in all my entries from the HashMap again I get duplicates.

How can I sort by values without creating duplicates?

CODE

public class Test {
    public static void main(String[] args) {

        HashMap<Integer, String> hMap = new HashMap<Integer, String>();
        ValueComparator vc = new ValueComparator(hMap);
        TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(vc);

        hMap.put(0, "b");
        hMap.put(1, "c");
        hMap.put(2, "a");
        tMap.putAll(hMap);
        tMap.putAll(hMap);

        for (Map.Entry<Integer, String> entry : tMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}

class ValueComparator implements Comparator<Integer> {
    Map<Integer, String> base;

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

    public int compare(Integer a, Integer b) {
        if (base.get(a).charAt(0) >= base.get(b).charAt(0))
             return 1;
        else return -1;
    }
}

OUTPUT

2 a
2 a
0 b
0 b
1 c
1 c

Solution

  • You need to modify logic as below, handle all three cases of -1, 0 and 1

    public int compare(Integer a, Integer b) {
            if (base.get(a).charAt(0) == base.get(b).charAt(0))
                return 0;
    
            else if (base.get(a).charAt(0) > base.get(b).charAt(0))
                return 1;
    
            else
                return -1;
        }
    

    output

    2 a
    0 b
    1 c