reiley
reiley

Reputation: 3761

Comparator's compare() function removing duplicates from a Map

I've a SortedMap which have items like:

Values can be duplicate.

I want to display the value-set on screen in the sorted manner. i.e.

myListMap

To sort the Map, I'm using comparator:

public class SortMapByValueComparator implements Comparator<String> {

    Map<String, String> mInputMap;

    /**
     * Constructor.
     * 
     * @param inputMap
     */
    public SortMapByValueComparator(Map<String, String> inputMap) {
        mInputMap = inputMap;
    }

    @Override
    public int compare(String lhs, String rhs) {
        String string1 = mInputMap.get(lhs);
        String string2 = mInputMap.get(rhs);
        return string1.compareToIgnoreCase(string2);
    }

}

And then passing the Map to this comparator like:

SortMapByValueComparator sortMapByValueComparator = new SortMapByValueComparator(myListMap);
SortedMap<String, String> sortedMapByValue = new TreeMap<String, String>(sortMapByValueComparator);
sortedMapByValue.putAll(myListMap);

Now, issue is when I call SortMapByValueComparator, it removes duplicate values. How can I avoid it?

PS - I want to use Map only.

Upvotes: 3

Views: 1699

Answers (2)

anvarik
anvarik

Reputation: 6487

The problem is that compareToIgnoreCase() is returning 0 when two strings are equal, and returning zero is merging the keys as it is explained here. Implement your compare in a way that zero is not returned, it should work fine.

if(string1.compareToIgnoreCase(string2) >= 0)
    return 1;
else 
    return -1;

Upvotes: 4

Mena
Mena

Reputation: 48404

I would change the whole approach and go with something simpler:

// initializing your Map
// not sure if key set is Integer or String but it doesn't really matter here
Map<Integer, String> tm = new TreeMap<Integer, String>();
tm.put(1, "abc");
tm.put(2, "xyz");
tm.put(3, "abc");
// getting the values as List (not Set, so duplicates allowed)
List<String>values = new ArrayList<String>(tm.values());
System.out.printf("Unsorted values: %s%n", values);
// sorting the values with natural (lexicographic) order...
Collections.sort(values);
System.out.printf("Sorted values: %s%n", values);

Output

Unsorted values: [abc, xyz, abc]
Sorted values: [abc, abc, xyz]

Upvotes: 1

Related Questions