How to sort a Map on the values in Java?
I am relatively new to Java, and often find that I need to sort a Map<Key, Value>
on the values. Since the values are not unique, I find myself converting the keySet
into an array
, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key. Is there an easier way?
Collections
Java
- asked 9 years ago
- B Butts
1Answer
Asuming Java ,you could sort hashmap just like this :
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;
}
Just a kick-off example , This way is more useful as it sorts the HashMap and keeps the duplicate values as well.
- answered 8 years ago
- Sunny Solu
Your Answer