Check Key in HashMap: containsKey() Method Explained
In a HashMap, you can use the containsKey() method to determine if a specified key exists in the HashMap. This method returns true if the key exists, otherwise it returns false.示例如下:
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("key1", 1);
hashMap.put("key2", 2);
if (hashMap.containsKey("key1")) {
System.out.println("Key 'key1' exists in the HashMap");
} else {
System.out.println("Key 'key1' does not exist in the HashMap");
}
if (hashMap.containsKey("key3")) {
System.out.println("Key 'key3' exists in the HashMap");
} else {
System.out.println("Key 'key3' does not exist in the HashMap");
}
In the example above, a HashMap object is first created and two key-value pairs are added to it. Then the containsKey() method is used to check if a specified key exists in the HashMap, and the corresponding message is displayed.