Iterate over map using entrySet()

Given a Map composed of String keys and Integer values, the following iterates over its entries using the entrySet() feature.

Map<String, Integer> map = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    // ...
}

Iterate over map using keySet()

Given a Map composed of String keys and Integer values, the following iterates over its entries using the keySet() feature.

Map<String, Integer> map = new HashMap<>();
for (String key : map.keySet()) {
    String value = map.get(key);
    // ...
}

Explanation

Java Maps are a powerful data structure capable of holding key/pair values, allowing developers to have something similar to a dictionary, where words are the key and the definition are the values. Iterating over these data structures is not as straightforward as it is for arrays or Lists, but the above code bits outline how this can be achieved. See more about the conversion of Map to List here.