Sorting a hash map
I need to sort the hashmap according to the key. The key is a string (so I need to sort it alphabetically) and the value is an integer. I tried searching on the internet and found that the tree set will automatically sort it as soon as you put it in. Can anyone guide me in the right direction as to how I could convert it to a set of trees, or maybe even if I could just sort it with a hashmap.
Thank you in advance
+3
source to share
1 answer
Since hashmaps are unsorted maps by definition, you will need to use a different container for this. There are several options depending on your needs, some of which are:
- Use
TreeMap
instead,HashMap
either temporarily or as a replacement. This would be the best option if you haven't saved the hashmap. - Use
TreeSet
to sort the keys and then iterate over the keys and extract the values ββfromHashMap
. - Do the same as option 2, but fill in a new one
LinkedHashMap
during iteration. This will render a map that returns values ββin insertion order, which happen to be sorted due to the use of a sorted set. Note that adding items toLinkedHashMap
will add all new items to the end -LinkedHashMap
still ordered by insertion order.
+6
source to share