Iterate over each Entry in a Map
If I have an object implementing the Map
interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?
Will the ordering of elements depend on the specific map implementation that I have for the interface?
2Answer
for (Map.Entry<String, String> entry : map.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
- answered 8 years ago
- Sunny Solu
Typical code for iterating over a map is:
Map<String,Thing> map = ...;
for (Map.Entry<String,Thing> entry : map.entrySet()) {
String key = entry.getKey();
Thing thing = entry.getValue();
...
}
HashMap
is the canonical map implementation and doesn't make guarantees (or though it should not change order if no mutating operation are performed on it). SortedMap
will return entries based on the natural ordering of the keys, or a Comparator
, if provided. LinkedHashMap
will either return entries in insertion-order or access-order depending upon how it has been constructed. EnumMap
returns entries in natural order of keys.
Note, IdentityHashMap
entrySet
iterator currently has a peculiar implementation which returns the same Map.Entry
instance for every item in the entrySet
! However, every time a new the iterator advances the Map.Entry
is updated.
- answered 8 years ago
- G John
Your Answer