• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Looping through HashMap

 
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 )
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic