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
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:
TreeMap instead of a HashMap either temporarily or as a replacement. This would be the best option unless you have to keep the hashmap.TreeSet to sort the keys, then iterate over the keys and extract the values from the HashMap.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With