It's not a secret anymore!
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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "iterate thru HashMap" Watch "iterate thru HashMap" New topic

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
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
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

Jim Yingst

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


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
I agree. Here's the link:
subject: iterate thru HashMap
It's not a secret anymore!