Library contents

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

  1. Start with A = 2
  2. Do this Look for key A
  3. Result Present
The letter identifies the entry. Two is the value stored at that key.

Syntax

Java syntax
register.containsKey(key)
Run these examples in Java

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

java Main.java

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

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

The key exists even though the mapped driver is null.

Advertisements

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.

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

GivenB12 → unassigned
Worked resultPresent

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.

Documentation for Map.containsKey and Map.containsValue