Java Map.putAll and Map.clear
Copy mappings from another map into a mutable destination. Source values replace destination values for matching keys.
A simple example
Map.putAll and Map.clear
- Start with A = 1, B = 2
- Do this Merge B = 3 and C = 4
- Result A = 1, B = 3, C = 4
Syntax
settings.putAll(overrides)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaApply weekend opening hours
A library keeps standard opening hours for every day, then receives a short list of weekend changes. The scheduler applies those overrides while preserving weekdays that the weekend list never mentions.
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var hours = new HashMap<>(Map.of("Mon", 9, "Sat", 9));
hours.putAll(Map.of("Sat", 10, "Sun", 11));
System.out.println(hours.get("Sat"));
}
}
10
The incoming Saturday value replaces nine with ten. Monday stays at nine.
Reset a completed shift register
The morning desk has handed every parcel to its owner and archived the shift report. It now clears the working register so the next shift starts with zero active tickets.
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var tickets = new HashMap<>(Map.of("P2", "Mira", "P8", "Sam"));
tickets.clear();
System.out.println(tickets.size());
}
}
0
clear removes all mappings and leaves the mutable register ready for reuse.
Decide whether a service desk can close
A service desk closes only after every open repair ticket has been collected. The shift supervisor checks whether any tickets remain and posts the current count for the next volunteer.
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var tickets = Map.of("R2", "Boiler", "R4", "Tap");
System.out.println(tickets.isEmpty() ? "Close the desk" : tickets.size() + " tickets open");
}
}
2 tickets open
isEmpty checks whether any mappings exist, and size counts distinct ticket numbers.
What to watch for
putAll replaces a whole value at each key. It does not recursively merge nested maps.