When I iterate over the values or keys are they going to correlate? Will the second key map to the second value?
views:
2942answers:
9The question confused me at first but @Matt cleared it up for me.
Consider using the entrySet() method that returns a set with the key-value pairs on the Map.
Map<Integer, Integer> a = new HashMap<Integer, Integer>(2);
a.put(1, 2);
a.put(2, 3);
for (Map.Entry<Integer, Integer> entry : a.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
This outputs:
1 => 2
2 => 3
3 => 3
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.
Both values() and keySet() delegate to the entrySet() iterator so they will be returned in the same order. But like Alex says it is much better to use the entrySet() iterator directly.
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
}
You want to use this, LinkedHashMap, for predicable iteration order
I second @basszero. While
for (Map.Entry<Integer, Integer> entry : a.entrySet())
will work, I find using a data structure that does this automatically is nicer. Now, you can just iterate "normally"
HashMap's keySet method returns a Set, which does not guarantee order.
HashMap's values() method returns a Collection, which does not guarantee order.
That said, the question was "are they going to correlate" so technically the answer is maybe, but don't rely on it.
public class Test { public static void main(String[] args) { HashMap hashmap = new HashMap(); hashmap.put("one", "1"); hashmap.put("two", "2"); hashmap.put("three", "3"); hashmap.put("four", "4"); hashmap.put("five", "5"); hashmap.put("six", "6");
Iterator keyIterator = hashmap.keySet().iterator(); Iterator valueIterator = hashmap.values().iterator();
while(keyIterator.hasNext()) { System.out.println("key: "+keyIterator.next()); }
while(valueIterator.hasNext()) { System.out.println("value: "+valueIterator.next()); }
}
}
key: two key: five key: one key: three key: four key: six value: 2 value: 5 value: 1 value: 3 value: 4 value: 6