To check if a key exists in a HashMap in Java, you can use the containsKey() method. Similarly, to check if a value exists in a HashMap, you can use the containsValue() method.
Here's an example that demonstrates both scenarios:
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Creating a HashMap
Map hashMap = new HashMap<>();
// Adding key-value pairs to the HashMap
hashMap.put("Key1", 1);
hashMap.put("Key2", 2);
hashMap.put("Key3", 3);
// Checking if a key exists using containsKey()
String keyToCheck = "Key2";
if (hashMap.containsKey(keyToCheck)) {
System.out.println("The key '" + keyToCheck + "' exists in the HashMap.");
} else {
System.out.println("The key '" + keyToCheck + "' does not exist in the HashMap.");
}
// Checking if a value exists using containsValue()
int valueToCheck = 3;
if (hashMap.containsValue(valueToCheck)) {
System.out.println("The value " + valueToCheck + " exists in the HashMap.");
} else {
System.out.println("The value " + valueToCheck + " does not exist in the HashMap.");
}
}
}
In this example, we create a HashMap called hashMap and add three key-value pairs using the put() method. Then, we demonstrate how to check if a key exists using the containsKey() method. We specify the key to check in the keyToCheck variable. If the key exists in the HashMap, the corresponding message is printed; otherwise, a different message is printed.
Next, we show how to check if a value exists in the HashMap using the containsValue() method. We specify the value to check in the valueToCheck variable. If the value exists in the HashMap, the corresponding message is printed; otherwise, a different message is printed.
The output of this example will be:
The key 'Key2' exists in the HashMap.
The value 3 exists in the HashMap.
As you can see, the program correctly identifies that the key "Key2" exists in the HashMap, and the value 3 also exists in the HashMap.