3

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

bawa
  • 93
  • 1
  • 1
  • 7
  • 2
    You could use a TreeMap. You can create a TreeMap using the constructor that takes a Map as parameter. – user2336315 Nov 05 '14 at 16:45
  • You can't sort a HashMap, since a HashMap stores elements unordered. You first have to convert it to another datastructure, like a List/Array/TreeMap etc. – quant Nov 05 '14 at 16:50

1 Answers1

6

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.
Thomas
  • 87,414
  • 12
  • 119
  • 157
  • 1
    No, I dont "have" to use a hashmap, I just used it from the start and I realised that its a unsorted map(I'm a bit of a amateur). So, if I replace it with a TreeMap instead, would it get sorted automatically? – bawa Nov 05 '14 at 16:58
  • @bawa yes, The things you add to TreeMap are sorted automatically. – nullptr Nov 05 '14 at 17:14