You can only use the extended for-loop over objects that implement the Iterable
interface. Map
does not.
However it provides some utility method to access collections of its entries, keys and values which are of type Iterable
. Therefore consider the following examples:
HashMap<A, B> map = new HashMap<>();
// Entries
for (Map.Entry<A, B> entry : map.entrySet()) { ... }
// Keys
for (A key : map.keySet()) { ... }
// Values
for (B value : map.values()) { ... }
Here are links to the documentation of all three methods:
Note that all three accesses are fast, O(1)
. As you get collections that are internally used by the map. That is also why they are backed by the map, which means if you change something on the collections or the entries, the changes will be reflected inside the map too.