This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Looping through HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Looping through HashMap " Watch "Looping through HashMap " New topic
Author

Looping through HashMap

Frank Sikuluzu
Ranch Hand

Joined: Dec 16, 2003
Posts: 116
I created a HashMap putting values and keys, the keys are like "01", "02", "03" kind two digits string. The when I loop through the HashMap, I use

Set set= hm.keySet();
Iterator iter = set.iterator();
while(iter.hasNext()){
String currentKey = iter.next();
// print out this currentKey
}

The print out result shows it is NOT ordered by "01", "02", "03" or alphabetical letter order, which was what I expected.

Why ? and how do I get a loop that output keys in alphabetical letter or digital ascendant order ?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24051
    
  13

Hi Frank,

HashMap does indeed store its keys in a seemingly random order. It's not really random, of course -- the order is related to the hashCode() values of the keys -- but it's not any kind of useful sorted order.

If you want a map in which they keys are kept in sorted order, use java.util.TreeMap instead. You pay for that sorting by giving up a little performance, but in many circumstances this really doesn't matter.


[Jess in Action][AskingGoodQuestions]
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
Use a TreeMap since that guarantees natural ordering. If the natural order is not what you want you can create a treemap with your own comparator:

TreeMap( Comparator c )
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Looping through HashMap
 
Similar Threads
Hwo to get set of Dates between two limits ?
bug with records.put(currentKey, record) ?
using EL to get the keySet of a HashMap
HashMap and Vector
what data structure is good for this problem ?