.containsKey()
The .containsKey()
method is declared in the Map
interface and is implemented in the HashMap
class. It is used to determine if a Map
object contains a specific key. The function returns a boolean value true
if the key exists, and false
if not.
Syntax
The .containsKey()
method can be called on a HashMap
instance and it requires one parameter, the key that needs to be checked:
hashMap.containsKey(key);
key
: This can take on the form of any type ofObject
.
Example
In the example below, the .containsKey()
method is used to check for the presence of the keys Apples
and Bananas
within a HashMap
:
import java.util.HashMap;public class Groceries {public static void main(String[] args) {// creating a new HashMap which maps string keys to integer valuesHashMap<String, Integer> basket = new HashMap<String, Integer>();// adding fruits to the basketbasket.put("Apples", 50);basket.put("Oranges", 30);// check if "Apples" is a keySystem.out.println("Basket contains Apples: " + basket.containsKey("Apples"));// check if "Bananas is a keySystem.out.println("Basket contains Bananas: " + basket.containsKey("Bananas"));}}
The above example will give the following output:
Basket contains Apples: trueBasket contains Bananas: false
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.