Sobes.tech
Junior — Middle

Does the Map class implement the Iterable interface and can it be iterated over in a for-each loop?

sobes.tech AI

Answer from AI

The Map interface in Java does not inherit from the Iterable interface. This means that objects of type Map cannot be directly iterated over in a for-each loop.

However, Map has methods that return collections implementing Iterable, such as:

  • keySet() — returns a set of keys,
  • values() — returns a collection of values,
  • entrySet() — returns a set of key-value pairs (Map.Entry).

These collections can be iterated over in a for-each loop.

Example of iterating over Map elements:

Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}