Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using a HashMap are values and keys guaranteed to be in the same order when iterating?

When I iterate over the values or keys are they going to correlate? Will the second key map to the second value?

like image 430
Allain Lalonde Avatar asked Sep 24 '08 15:09

Allain Lalonde


2 Answers

No, not necessarily. You should really use the entrySet().iterator() for this purpose. With this iterator, you will be walking through all Map.Entry objects in the Map and can access each key and associated value.

like image 107
Alex Miller Avatar answered Nov 01 '22 13:11

Alex Miller


to use the entrySet that @Cuchullain mentioned:

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

// populate hashmap

for (Map.Entry<String, String> entry : map.entrySet()) {
  String key = entry.getKey();
  String value = entry.getValue();
  // your code here
}
like image 38
Matt Avatar answered Nov 01 '22 13:11

Matt