Prof. Falken
Prof. Falken

Reputation: 24917

How to sort the values of a HashMap in Java and keep the duplicate entries?

I have been looking for an answer to this and could not find it on SO. So I thought I might share with you all. I want to sort on values, not keys.

Upvotes: 2

Views: 3055

Answers (3)

Prof. Falken
Prof. Falken

Reputation: 24917

And the answer, I found here.

    public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
    List mapKeys = new ArrayList(passedMap.keySet());
    List mapValues = new ArrayList(passedMap.values());
    Collections.sort(mapValues);
    Collections.sort(mapKeys);

    LinkedHashMap sortedMap = 
        new LinkedHashMap();

    Iterator valueIt = mapValues.iterator();
    while (valueIt.hasNext()) {
        Object val = valueIt.next();
        Iterator keyIt = mapKeys.iterator();

        while (keyIt.hasNext()) {
            Object key = keyIt.next();
            String comp1 = passedMap.get(key).toString();
            String comp2 = val.toString();

            if (comp1.equals(comp2)){
                passedMap.remove(key);
                mapKeys.remove(key);
                sortedMap.put((String)key, (Double)val);
                break;
            }
        }
    }

    return sortedMap;
}

Upvotes: 2

Balaji
Balaji

Reputation: 757

public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
List mapKeys = new ArrayList(passedMap.keySet());
List mapValues = new ArrayList(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);

LinkedHashMap sortedMap = 
    new LinkedHashMap();

Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
    Object val = valueIt.next();
    Iterator keyIt = mapKeys.iterator();

    while (keyIt.hasNext()) {
        Object key = keyIt.next();
        String comp1 = passedMap.get(key).toString();
        String comp2 = val.toString();

        if (comp1.equals(comp2)){
            passedMap.remove(key);
            mapKeys.remove(key);
            sortedMap.put((String)key, (Double)val);
            break;
        }

    }

}
return sortedMap;

}

Upvotes: 1

Can't Tell
Can't Tell

Reputation: 194

This is a different approach that can be used. The compare() method in the Comparator does not return 0 on equal. This will keep the duplicate entries.

Upvotes: 3

Related Questions