I have a hashmap, I wish to get an array of the values in this hashmap, but I wish for the array to be sorted by the keys in the hashmap.
For instance if the map looks like this:
- <2,obj1>
- <4,obj2>
- <0,obj3>
- <10,obj4>
- <5,obj5>
- <1,obj6>
- <15,obj7>
- <3,obj8>
I want the array to be: [obj3,obj6,obj1,obj8,obj2,obj5,obj4,obj7]
The faster the better. Is there a built in way to do this?
Sounds like you want a
SortedMap, specifically aTreeMap. You can use the fact that the map maintains a sorted list of keys to generate your output array, e.g. by usingSortedMap.values()or by iterating over the entries in the map.