Library contents

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

  1. Start with A = 1, B = 2
  2. Do this Merge B = 3 and C = 4
  3. Result A = 1, B = 3, C = 4
One input key replaces an existing value and one introduces a new key.

Syntax

Java syntax
settings.putAll(overrides)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Apply 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.

Result10
Main.java
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"));
    }
}
Output
10

The incoming Saturday value replaces nine with ten. Monday stays at nine.

Advertisements

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.

Result0
Main.java
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());
    }
}
Output
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.

Result2 tickets open
Main.java
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");
    }
}
Output
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.

Documentation for Map.putAll and Map.clear