2

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.

2
  • just out of curiosity, if you wanted a sorted map, why not use TreeMap? Commented Mar 2, 2010 at 10:00
  • 1
    Probably because a TreeMap sorts keys, and OP wants to sort values. Commented Mar 2, 2010 at 11:25

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;
}

1 Comment

Glad to know it helped someone, @Sunny.
1
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;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.