This is another way to sort a HashMap. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.
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;
}
fantastic, the best i found
fantastic, the best i found so far
Wow thanks for the great
Wow thanks for the great information. I was searching how to sort Hashmap using Java for quite a long time.I have tried many different ways to do that but your way is definitely the best. Of course the best thing about it is that it keeps the duplicat values. Thanks one more time for this pretty piece of code and I will be waiting for another great ones from you.
Sincerely,
Jeff Markson from java software development
help
How to sort by descending order
In the source code above, after the 5th line...
you enter the following simple code:Everything else remains the same. Test it! It should work... report back the result please!
Good solution
Good solution
Gr8
Its a good procedure
Super
thank you
Thank you this is very informative! It's a good procedure...
its the best way to sort
Perfect
Post new comment