Video in progress
Do HashMap's keySet(), values() and entrySet() return copies? What happens if you remove an element through them or call setValue?
None of them is a copy; each is a live window onto the Map. If you call remove, removeIf or retainAll on them, the entry disappears from the Map too, and entry.setValue replaces the value in place. Only add doesn't work.
📖 Answer
Map<String, Integer> stock = new HashMap<>(Map.of("olma", 0, "nok", 5, "anor", 0));
stock.values().removeIf(q -> q == 0); // entries with stock 0 are gone from the Map
stock.keySet().retainAll(allowedSkus); // the ones that aren't allowed are gone too
for (var e : stock.entrySet()) {
e.setValue(e.getValue() * 2); // no CME: the structure didn't change
}
stock.keySet().add("behi"); // UnsupportedOperationException
These views are created once inside HashMap and kept in a field. So calling keySet() is cheap, since nothing is copied.
In practice you run into this from two sides.
The upside: to "remove the entries whose value matches a condition" you don't need to collect a separate list and then remove one by one. values().removeIf(...) or entrySet().removeIf(e -> ...) does it in one pass.
The danger: handing the view out. If a getter does return map.keySet();, the caller can modify your Map through remove. Or you keep the view in a field, and when the Map changes you wonder why it "changed by itself". If you have to hand it out, use Set.copyOf(map.keySet()) or Collections.unmodifiableSet(...).
One more thing: ConcurrentHashMap.keySet(defaultValue) works differently. You can call add on the set it returns, and an entry with that default value is added to the Map.
Sign up to mark studied questions and save your progress.