File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes iterate thru HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "iterate thru HashMap" Watch "iterate thru HashMap" New topic
Author

iterate thru HashMap

lavnish lalchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 79
the following code




gives me output

3...object name t-h-r-e-e
2...object name t-w-o
1...object name o-n-e

but what i want is

1...object name o-n-e
2...object name t-w-o
3...object name t-h-r-e-e

I need the above output for correct functionality of my application ...
am ok in using another collection object .. like HashTable !!
how do i achieve the above output


lavnish.blogspot.com
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3654
    
  15
Originally posted by lavnish lalchandani:
how do i achieve the above output


By not using a HashMap !
From the java doc for HashMap
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.


If order is important use a LinkedHashMap


Joanne
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Joanne]: If order is important use a LinkedHashMap

Or possibly a TreeMap. In this example they will both give the same output. But if you change

to

then the LinkedHashMap will iterate in the order the items were added (3-2-1) while the TreeMap will iterate in the natural order of the keys (1-2-3). Choose whichever behavior seems more appropriate for your application.


"I'm not back." - Bill Harding, Twister
 
Don't get me started about those stupid light bulbs.
 
subject: iterate thru HashMap