It's not a secret anymore!
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
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

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,
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15084

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 8 API documentation
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

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

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

I agree. Here's the link:
subject: how to change order of putting <keys,values> in hashMap
It's not a secret anymore!