• 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

Hashmap in java

 
Ranch Hand
Posts: 293
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi friends, i need sample code to retrieve objects from HashMap in ascending order . Thanks Prakash
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I suppose you want to sort by the keys which are Strings.

You cannot directly sort a HashMap, it's not made for that. The only workaround would be extracting the keySet() and sorting that, then iterating over the keySet.

But since there is a TreeMap, which does sorting for you, you can simply use that.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As Sebastian said, HashMap does not preserve any order at all. You can use TreeMap which uses Comparable's compareTo method or Comparator's compare method for determining the order, or LinkedHashMap which uses insertion order. The latter can be changed to be the last-accessed order instead by specifying this in the constructor.
 
Ranch Hand
Posts: 257
Hibernate Oracle Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can use this sample code -



The result of this program is {1=Testing, 10=Sample, 20=First, 30=Second}.
In this case I have used Integer as a key to it is giving the result in ascending order by key. But if you are using any other object they you shall have to check that the object has implemented the comparable interface in it

Regards
Salil Verma



 
Slideshow boring ... losing consciousness ... just gonna take a quick nap on this tiny ad ...
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic