Video in progress
What is the most convenient and cheapest way to iterate over a Map?
When you need both the key and the value, use entrySet() or forEach((k, v) -> ...). Walking over keySet() and calling get() for every key does an extra lookup.
📖 Answer
Beginners often write this:
for (String key : prices.keySet()) {
int p = prices.get(key); // one more hash lookup on every step
}
It works, but you do the work twice. And in a TreeMap every get is O(log n).
Better options:
for (Map.Entry<String, Integer> e : prices.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
prices.forEach((name, price) -> System.out.println(name + " = " + price));
If you only need the values, use prices.values(). If you want to change a value during iteration, use entry.setValue(...) or prices.replaceAll((k, v) -> v * 2), not put, or you will get a ConcurrentModificationException when it ends up adding a new key.
Sign up to mark studied questions and save your progress.