1

Possible Duplicate:
ordered map implementation

I am using the hashmap to store the values as follows -

 Map<String,String>         propertyMap=new HashMap<String,String>();


 propertyMap.put("Document Type", dataobject.get("dDocType"));
 propertyMap.put("Document Title", dataobject.get("dDocTitle"));
 propertyMap.put("Revision Label", dataobject.get("dRevLabel"));
 propertyMap.put("Security Group", dataobject.get("dSecurityGroup"));

After that i am getting the hashmap key and value in a List

 documentProperties = new ArrayList(propertyMap.entrySet());

But when i iterate over the List i am not getting the key and values in the order i have put it into the map..

Is there is anyway by which i can get the values in the Order i am putting it into the map. Thanks

Community
  • 1
  • 1
Durgesh Sahu
  • 247
  • 1
  • 5
  • 19

4 Answers4

2

I believe what you are looking for is LinkedHashMap.

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

By the why, why the need for a separate ArrayList? You can directly iterate over Map.entrySet:

for (final Map.Entry<String, String> entry : propertyMap.entrySet()) {
  ...
}
obataku
  • 29,212
  • 3
  • 44
  • 57
Ajay George
  • 11,759
  • 1
  • 40
  • 48
0

propertyMap.entrySet() you get results as Set. Set is un-ordered.

new ArrayList(propertyMap.entrySet()); constructs a list with the order you have in Set (which may not be the order you have put into map).

If you are looking for order map, you may use LinkedHashMap

Here is interesting discussion on this topic.

kosa
  • 65,990
  • 13
  • 130
  • 167
0

You have to use LinkedHashMap. For more details Please check this question and answer given by Michael

Community
  • 1
  • 1
Patton
  • 2,002
  • 3
  • 25
  • 36
0

Try this..

for(Map.Entry<String, String> m : map.entrySet()){


       // Use m.getKey() to get the Key.
       // Use m.getValue() to get the Value.
}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75