开发者

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

开发者 https://www.devze.com 2022-12-21 12:27 出处:网络
I have been looking for an answer to this and could not find it on SO. So I thought I might share with yo开发者_运维知识库u all. I want to sort on values, not keys.This is a different approach that ca

I have been looking for an answer to this and could not find it on SO. So I thought I might share with yo开发者_运维知识库u all. I want to sort on values, not keys.


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.


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


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;

}

0

精彩评论

暂无评论...
验证码 换一张
取 消