I have a sorting issue with a Hashmap. My constraint is that I MUST use the Hashmap and work with existing code. I do a database query and place the results in a Hashmap. When I iterate thru the Hashmap, it loses the original alphabetical sorting done by the database. So, my problem is that I must sort the results coming out of the Hashmap which is then placed into another class.
There is no problem with your HashMap implementation but the problem is the iterator that you are using. the HashMap class does not have an iterator of its own. it just returns you an object of type Set and we have to obtain our iterator from this Set object. Remember a Set does NOT ensure sorted Data but it does ensure uniqueness of data. so an iterator from the set provides you unsorted unique data. if you wish to sort it you have to pass this Set object to a SortedSet Object. TreeSet is considered to be the Only SortedSet implementation.
So i must say that i have provided you the reason why Srikanth is correct.
As for the sorting problem:
1) a HashMap is unsorted. There is nothing you can do about that. A LinkedHashMap can keep the insertion order, but that's as far as you get in regards to the order.
2) A SortedMap (with TreeMap as the most used implementation) is the only option when you want to sort on the keys.
3) Sorting on values is not possible in the current Map implementations. You would need to write one of your own. This topic has been addressed many times before; if you search on this forum you should get multiple results.
If you want alphabetical sorting you can use a TreeMap as both Srikanth Nut and shukla raghav have suggested. If the database provides this same ordering you can also use a LinkedHashMap.