The syntax of the containsKey()
method is:
hashmap.containsKey(Object key)
Here, hashmap is an object of the HashMap
class.
containsKey() Parameter
The containsKey()
method takes a single parameter.
- key - mapping for the key is checked in the hashmap
containsKey() Return Value
- returns
true
if the mapping for the specified key is present in the hashmap - returns
false
if the mapping for the specified key is not present in the hashmap
Example 1: Java HashMap containsKey()
import java.util.HashMap;
class Main {
public static void main(String[] args){
// create a HashMap
HashMap<String, String> details = new HashMap<>();
// add mappings to HashMap
details.put("Name", "codemy");
details.put("Domain", "codemy.com");
details.put("Location", "Nepal");
System.out.println("codemy Details: \n" + details);
// check if key Domain is present
if(details.containsKey("Domain")) {
System.out.println("Domain name is present in the Hashmap.");
}
}
}
Output
codemy Details: {Domain=codemy.com, Name=codemy, Location=Nepal} Domain name is present in the Hashmap.
In the above example, we have created a hashmap. Notice the expressions,
details.containsKey("Domain") // returns true
Here, the hashmap contains a mapping for the key Domain. Hence, the containsKey()
method returns true
and statement inside if
block is executed.
Example 2: Add Entry to HashMap if Key is already not present
import java.util.HashMap;
class Main {
public static void main(String[] args){
// create a HashMap
HashMap<String, String> countries = new HashMap<>();
// add mappings to HashMap
countries.put("USA", "Washington");
countries.put("Australia", "Canberra");
System.out.println("HashMap:\n" + countries);
// check if key Spain is present
if(!countries.containsKey("Spain")) {
// add entry if key already not present
countries.put("Spain", "Madrid");
}
System.out.println("Updated HashMap:\n" + countries);
}
}
Output
HashMap: {USA=Washington, Australia=Canberra} Updated HashMap: {USA=Washington, Australia=Canberra, Spain=Madrid}
In the above example, notice the expression,
if(!countries.containsKey("Spain")) {..}
Here, we have used the containsKey()
method to check if a mapping for Spain is present in the hashmap. Since we have used the negate sign (!
), the if
block is executed if the method returns false
.
Hence, the new mapping is added only if there is no mapping for the specified key in the hashmap.
Note: We can also use the HashMap putIfAbsent() method to perform the same task.