I am sorry for posting this unclear question. This is my first time using hashmap and hence i was confused. Have tried to explain this question in a better way here - store key values of hashmap in string[]
I have a sorted hashmap based on values. I want to extract the keys from the sorted map and store them in a String[] array. The order of the keys(sorted by values) is important. I used this code to sort the hashmap on values - http://www.xinotes.org/notes/note/306/
To extract the key array, I tried
String[] keys = (String[])( hm.keySet().toArray( new String[hm.size()] ) )
(here hm is the hashmap)
But this method didnt work. The keys string[] has the keys but not in the sorted order I want.
Update: I used linkedHashMap and was able to store the sorted key values in an array. Here is the link for the code.
It would seem that you want the order of the keys of a
HashMap
to be the same as your sorted list of keys. This is simply not possible. AHashMap
s keys are determined by the hash table algorithms; e.g. a complicated process that depends on the keys' hash values and sequence of insertions and deletions.The closest you will get is to create a
LinkedHashMap
, and populate it by inserting entries from the oldHashMap
in the order of the sorted keys. If you then iterate over theLinkedHashMap
's keys, you will get them back in the order in which they were inserted. But this is a heavy-weight solution, and it breaks down if you subsequently have to add more entries to the "sorted" map. It may be better to just use aTreeMap
.In that case, you simply need to extract the HashMap's keys into an array and sort it. The code has been given in other answers.
On the other hand, if you want to do something so that the map's keys always come out in the sorted order (which you seem to be saying in other comments), you are changing the map.
No you haven't. A HashMap isn't sorted at all. You can get the values(), as a Collection, and you can sort that any way you like, but it doesn't sort the HashMap itself.
It isn't defined to do anything differently, especially as you haven't sorted the HashMap at all.
You need to clarify what you're talking about here. If you want to sort the values, do the above. If you want to sort the keys, do the above with
keys()
instead ofvalues()
'. If you want the Map itself sorted on keys, use a TreeMap. If you want the Map itself sorted on values, bad luck, you can't.HashMap uses key.hashValue() to sort the values. Use TreeMap instead.
Try this:
The output would be:
Based on the typo, and your clarification that you are using hashmap, the order of the keys retrieval will not be consistent with the insert order. Use LinkedHashMap for that. This is using you do external sorting and then insert sorted entries into the map.
If you want the entries to be sorted while they are being inserted into the Map, use TreeMap. You can either use a custom comparator or make your key object implement Comparable interface.