my dog learned polymorphism*
The moose likes Java in General and the fly likes  Hashmap in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark " Hashmap in java" Watch " Hashmap in java" New topic
Author

Hashmap in java

Rajendra Prakash
Ranch Hand

Joined: Sep 10, 2009
Posts: 293
Hi friends, i need sample code to retrieve objects from HashMap in ascending order . Thanks Prakash
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
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.


JDBCSupport - An easy to use, light-weight JDBC framework -
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Salil Vverma
Ranch Hand

Joined: Sep 06, 2009
Posts: 253

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




Regards
Salil Verma
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Hashmap in java
 
Similar Threads
Nested if's
struts 2 s:radio tag
Finding a Specific Object in an ArrayList
WA #1.....word association
switch on String