This question already has an answer here:
- Sort a Map<Key, Value> by values 49 answers
I need to sort my HashMap
according to the values stored in it. The HashMap
contains the contacts name stored in phone.
Also I need that the keys get automatically sorted as soon as I sort the values, or you can say the keys and values are bound together thus any changes in values should get reflected in keys.
HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"froyo");
map.put(2,"abby");
map.put(3,"denver");
map.put(4,"frost");
map.put(5,"daisy");
Required output:
2,abby;
5,daisy;
3,denver;
4,frost;
1,froyo;
Assuming Java, you could sort hashmap just like this:
Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.
Try below code it works fine for me. You can choose both Ascending as well as descending order
Edit: Version 2
In Java 8:
You don't, basically. A
HashMap
is fundamentally unordered. Any patterns you might see in the ordering should not be relied on.There are sorted maps such as
TreeMap
, but they traditionally sort by key rather than value. It's relatively unusual to sort by value - especially as multiple keys can have the same value.Can you give more context for what you're trying to do? If you're really only storing numbers (as strings) for the keys, perhaps a
SortedSet
such asTreeSet
would work for you?Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?