Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a hashmap

I need to sort a hash map according to the key.The key is a string(so I need to sort it alphabetically) and the value is an integer. I was trying to search online and found that tree set automatically sorts it once you put it. Could somebody guide me in the right direction as to how I could convert it into a tree set or maybe even if i could just sort it using a hash map.

Thanks in advance

like image 573
bawa Avatar asked Dec 10 '25 05:12

bawa


1 Answers

Since hashmaps are unsorted maps by definition you'd need to use another container for that. Depending on your needs there are several options, some being:

  1. Use a TreeMap instead of a HashMap either temporarily or as a replacement. This would be the best option unless you have to keep the hashmap.
  2. Use a TreeSet to sort the keys, then iterate over the keys and extract the values from the HashMap.
  3. Do the same as in option 2 but fill a new LinkedHashMap during iteration. This will result in a map that returns the values in insert order which happens to be sort order due to use of a sorted set. Note that adding elements to the LinkedHashMap will append any new elements to the end - LinkedHashMap is still ordered by insertion order.
like image 128
Thomas Avatar answered Dec 12 '25 17:12

Thomas