• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

iterate thru HashMap

 
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[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.
 
Willie Smits increased rainfall 25% in three years by planting trees. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic