When you need both the key and value during iteration, .entrySet() is more efficient than .keySet() plus .get(). It returns a set of Map.Entry objects, each holding one key-value pair:
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
String name = entry.getKey();
int age = entry.getValue();
System.out.println(name + " is " + age);
}
Each Map.Entry gives you direct access to both the key and value without a second lookup. For large maps, this saves time compared to calling .get() inside a .keySet() loop.
You can also call .values() if you only need the values and do not care about the keys. It returns a Collection<V> that you can loop through with a for-each.