File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes how to change order of putting <keys,values> in hashMap 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 » Beginning Java
Bookmark "how to change order of putting <keys,values> in hashMap" Watch "how to change order of putting <keys,values> in hashMap" New topic
Author

how to change order of putting <keys,values> in hashMap

srikanth Thandra
Ranch Hand

Joined: Mar 04, 2009
Posts: 42
Dear All,

I am getting some column names from database like Request_id,Name,Address,Request_status.
Now i am putting the above values as key in a hash Map. When i display the hash Map the order it is showing as Name,Address,Request_status,Request_id.

My requirement is i want the Request_id at first in hash map when displaying. Is there any way to do that.

I have used Tree Map but it gives sorted map and displays Address,Name,Request_id,Request_status. This is not my requirement since it displays Request_id at 3rd place. I want Request_id at 1st place.


Please give me suggestions on achieving this. Waiting for the reply.


Thanx in advance,
Srikanth
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

A HashMap does not have an order. You can view a HashMap as a bag that contains a number of items - the items are jumbled up in the bag, and not in any particular order.

You can use LinkedHashMap instead of HashMap, which keeps the entries in the order that you inserted them.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

I would argue that if you want a certain value at a certain place, you don't want to use a map at all.

If you always want Name to be first, what's wrong with an ArrayList?


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3418
    
  12
Or create a class to hold the values and override the toString method to print them in the order you want.


Joanne
 
 
subject: how to change order of putting <keys,values> in hashMap
 
Similar Threads
Overriding Hash()
JavaScript cookie with Hash value
Map Issues
problem with hash map
Base64 / MD5 Encoding & Decoding