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.
-
just out of curiosity, if you wanted a sorted map, why not use TreeMap?KitsuneYMG– KitsuneYMG2010-03-02 10:00:13 +00:00Commented Mar 2, 2010 at 10:00
-
1Probably because a TreeMap sorts keys, and OP wants to sort values.Adriaan Koster– Adriaan Koster2010-03-02 11:25:03 +00:00Commented Mar 2, 2010 at 11:25
Add a comment
|
3 Answers
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.
Comments
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
Prof. Falken
Glad to know it helped someone, @Sunny.
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;
}