Java Map.containsKey and Map.containsValue
Test for a key independently of its value, or test whether at least one mapping holds a given value.
A simple example
Map.containsKey and Map.containsValue
- Start with A = 2
- Do this Look for key A
- Result Present
Syntax
register.containsKey(key)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFind a parcel whose driver is still unassigned
A dispatch desk registers parcels before assigning drivers. Parcel P7 already has a record with an empty assignment, and the operator must distinguish it from a parcel that has never been registered.
import java.util.HashMap;
class Main {
public static void main(String[] args) throws Exception {
var drivers = new HashMap<String, String>();
drivers.put("P7", null);
System.out.println(drivers.containsKey("P7") ? "Registered" : "Unknown");
}
}
Registered
The key exists even though the mapped driver is null.
See whether any room has a projector
A teacher wants to show a film during the next lesson. The equipment register maps rooms to their main device, and the teacher only needs to know whether a projector appears anywhere in it.
import java.util.Map;
class Main {
public static void main(String[] args) throws Exception {
var equipment = Map.of("A1", "Screen", "B2", "Projector");
System.out.println(equipment.containsValue("Projector") ? "Available" : "Book a rental");
}
}
Available
The value search finds the projector assigned to B2.
Find an unassigned booking
A clinic already has booking B12, although a clinician has yet to be assigned. The desk checks whether the identifier has a record before creating one. Is the key already present?
What to watch for
Looking up a key in a HashMap is generally cheaper than scanning its values. More than one key can have the same value.