Maps: keySet and values are views, not copies

Removing from keySet removes the whole entry from the map. That is powerful and easy to do by accident.

Code
Map<String, Integer> map = new TreeMap<>();
map.put("a", 1); map.put("b", 2); map.put("c", 3);

map.keySet().remove("b");
System.out.println("after keySet().remove(b): " + map);

map.values().removeIf(v -> v > 2);
System.out.println("after values().removeIf(v > 2): " + map);
Output
after keySet().remove(b): {a=1, c=3}
after values().removeIf(v > 2): {a=1}
Advertisement

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