Iterating keys and calling get for each one hashes every key twice. entrySet gives the key and value together in a single pass.
Map<String, Integer> tokens = new TreeMap<>();
tokens.put("ava", 60);
tokens.put("ben", 150);
for (Map.Entry<String, Integer> e : tokens.entrySet()) {
System.out.println(e.getKey() + " has " + e.getValue() + " tokens");
}
tokens.entrySet().forEach(e -> e.setValue(e.getValue() + 10));
System.out.println("setValue writes through: " + tokens);
ava has 60 tokens
ben has 150 tokens
setValue writes through: {ava=70, ben=160}
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30