Sorting of Map

Hi friendsIs there any way to sort a Hashtable based on its Key.
[85 byte] By [rajpuniaa] at [2007-10-3 3:17:23]
# 1
A HashTable (in fact, a Hash-anything) is, by definition, an unsorted datastructure. You can however, get the set of keys and sort that set. Have you tried this?
dannyyatesa at 2007-7-14 21:08:57 > top of Java-index,Core,Core APIs...
# 2
If you want a sorted map, try TreeMap.
Herko_ter_Horsta at 2007-7-14 21:08:57 > top of Java-index,Core,Core APIs...
# 3
> If you want a sorted map, try TreeMap.No!!!!!Suppose I am writingclass which Implements HashMap and in that class we can write a methos for sorting based on key.Please Suggest
rajpuniaa at 2007-7-14 21:08:57 > top of Java-index,Core,Core APIs...
# 4

You cannot "implement HashMap". HashMap is a class. You can extend it. Or you can implement the Map interface.

Have you read my reply? Hash-based structures are by definition unsorted.

You need to re-think what you want to do, or re-state your problem in more concrete terms so that people can understand it.

dannyyatesa at 2007-7-14 21:08:57 > top of Java-index,Core,Core APIs...
# 5

> You cannot "implement HashMap". HashMap is a class.

> You can extend it. Or you can implement the Map

> interface.

>

> Have you read my reply? Hash-based structures are by

> definition unsorted.

>

> You need to re-think what you want to do, or re-state

> your problem in more concrete terms so that people

> can understand it.

You mean to say that .We have to put the data after sorting it.

rajpuniaa at 2007-7-14 21:08:57 > top of Java-index,Core,Core APIs...
# 6

Hi,

I appreciate that English isn't your native tongue, but I'm struggling to understand you.

I will assume you meant your last message to be one sentance with a question mark at then end.

No. Putting sorted data into a hash-based structure will not solve the problem. Think about how a hashed structure (e.g. HashMap) works. Without additional help, there is no way of knowing what the "sorted" order of elements is. And sorted might be defined by some natural sorting order, or by order of insertion.

Short of using a non-hashed structure (e.g. a TreeMap as somebody else suggested), the only choice you have is to sort the data after you retrieve it.

Actually... if you are happy to sort the data prior to insertion, you could use LinkedHashMap which does maintain insertion order - but it does it at the cost of having to maintain both a HashMap and a LinkedList running through the same data.

dannyyatesa at 2007-7-14 21:08:58 > top of Java-index,Core,Core APIs...