Java HashMap containsKey() Method
The containsKey() method checks whether there is a mapping for the specified key in the hashMap.
The syntax of the containsKey() method is:
hashmap.containsKey(Object key)
Note:hashmap is an object of the HashMap class.
Parameters:
- key - the key
Return Value
If the hashMap contains a mapping for the specified key, it returns true; otherwise, it returns false.
Example
The following example demonstrates the use of the containsKey() method:
Example
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// Check whether key 1 exists
if(sites.containsKey(1)) {
System.out.println(Key 1 exists in sites);
}
}
}
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// Check whether key 1 exists
if(sites.containsKey(1)) {
System.out.println(Key 1 exists in sites);
}
}
}
Executing the above program produces the following output:
sites HashMap: {1=Google, 2=Example, 3=Taobao}
key 为 1 存在于 sites 中
For non-existent keys, we can perform an insert operation.
Example
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// Check whether key 4 exists; if not, insert the key/value pair
// Use the ! symbol to negate the boolean result
if(!sites.containsKey(4)) {
sites.put(4, "Wiki");
}
System.out.println("Updated sites HashMap: " + sites);
}
}
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// Check whether key 4 exists; if not, insert the key/value pair
// Use the ! symbol to negate the boolean result
if(!sites.containsKey(4)) {
sites.put(4, "Wiki");
}
System.out.println("Updated sites HashMap: " + sites);
}
}
Executing the above program produces the following output:
sites HashMap: {1=Google, 2=Example, 3=Taobao}
Updated sites HashMap: {1=Google, 2=Example, 3=Taobao, 4=Wiki}
Note:We can also useHashMap putIfAbsent() methodto perform the same operation.
Other Extensions
Java HashMap