my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Regarding sorting of TreeMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regarding sorting of TreeMap" Watch "Regarding sorting of TreeMap" New topic
Author

Regarding sorting of TreeMap

yekkala krishna
Ranch Hand

Joined: Mar 04, 2007
Posts: 105
Hi,

In my application elements are added to a TreeMap.so whenever we are retrieving elements are displaying in the sorted order of keys.But i want to retrieve the elements in the order in which they are inserted.May i know which will be the correct choice now to do this order?



Thanks in advance.

regards,
rama krishna.y
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Use a LinkedHashMap.


[My Blog]
All roads lead to JavaRanch
yekkala krishna
Ranch Hand

Joined: Mar 04, 2007
Posts: 105
Hi Verre,

Thanks for your reply.
Elements are displaying in the inserted order if i use LinkedHashMap.
Can i do the same thing using TreeMap?



regards,
Rama Krishna
amit punekar
Ranch Hand

Joined: May 14, 2004
Posts: 516
Hi,
But i want to retrieve the elements in the order in which they are inserted


You need to use LinkedHashMap to do this. If you use TreeMap then you are going to get the results in sorted manner based on the Key.

Regards,
Amit
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40029
    
  28
A collections class will display its elements in one order (or no particular order). They are not designed to display two different orders. If you want sorted order as well as insertion order, try your tree Map and a separate List, and add the same element to both. Or insert all your elements into the List and later pass both the key and value for every pair to the Map.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding sorting of TreeMap