If you want to check whether the specified key is present in the
HashMap or not you can use containsKey()
method in the java.util.Map which returns true only if Map contains a mapping for the specified key.
Syntax of the method is as given below.
containsKey(Object key)
key- key whose presence in this map is to be tested
Method returns true if this map contains a mapping for the specified key otherwise returns false.
containsKey() Java example
1. Here we have a map of items with item and its price as key, value pairs. If you want to check if the specified key is already there or not.
import java.util.HashMap;
import java.util.Map;
public class ContainsKeyDemo {
public static void main(String[] args) {
Map<String, Integer> itemMap = new HashMap<>();
itemMap.put("Trousers", 1200);
itemMap.put("Shirt", 800);
itemMap.put("Shoes", 2400);
itemMap.put("Belt", 750);
if(itemMap.containsKey("Shoes")) {
System.out.println("Item already present in the Map");
}
}
}
Output
Item already present in the Map
2. You can also use containsKey() method to add a new entry to the Map after checking that the key is already not there.
import java.util.HashMap;
import java.util.Map;
public class ContainsKeyDemo {
public static void main(String[] args) {
Map<String, Integer> itemMap = new HashMap<>();
itemMap.put("Trousers", 1200);
itemMap.put("Shirt", 800);
itemMap.put("Belt", 750);
boolean isItemShoeExist = itemMap.containsKey("Shoes");
System.out.println("Does key Shoes exist in the HashMap- " + isItemShoeExist);
if(!itemMap.containsKey("Shoes")) {
itemMap.put("Shoes", 2400);
}else {
System.out.println("Item already present in the Map");
}
System.out.println("Map Values- " + itemMap);
}
}
Output
Does key Shoes exist in the HashMap- false
Map Values- {Shirt=800, Belt=750, Shoes=2400, Trousers=1200}
As you can see when checking for the key which is not present in the Map, containsKey method returns false. Using that you can add a new entry to the HashMap.
That's all for this topic Java Map containsKey() - Check if Key Exists in Map. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment