• support@answerspoint.in

Iterate over each Entry in a Map

23
Advertisement

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


0
for (Map.Entry<String, String> entry : map.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue());
}
  • answered 10 years ago
  • Sunny Solu

0

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 10 years ago
  • G John

Your Answer

    Facebook Share        
       
  • publish 10 years ago
  • viewed 23 times
  • active 10 years ago

Best Rated Questions