Java HashMap.containsKey()

In this tutorial, we will learn about the Java HashMap.containsKey() function, and learn how to use this function to check if this HashMap contains specified key, with the help of examples.

containsKey(Object key)

HashMap.containsKey() returns true if this HashMap contains a mapping for the specified key. Else, containsKey() returns false.

The syntax of containsKey() function is

containsKey(Object key)

where

ParameterDescription
keyThe object which we are checking if present in this HashMap.

Returns

The function returns boolean value.

ADVERTISEMENT

Examples

1. containsKey( key) – Key present

In this example, we will initialize a HashMap hashMap with mappings from String to Integer. Using HashMap.containsKey() method, we will check if the key "A" is present in this hashMap. Since, the key "A" is present in hashMap, containsKey() should return true.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,Integer> hashMap = new HashMap<>();
		hashMap.put("A",1);
		hashMap.put("B",2);
		hashMap.put("C",3);
		hashMap.put("D",4);
		
		boolean result = hashMap.containsKey("A");
		System.out.println("Does the HashMap contains key 'A' ? : " + result);
	}
}

Output

Does the HashMap contains key 'A' ? : true

2. containsKey(key) – Key not present

In this example, we will initialize a HashMap hashMap with mappings from String to Integer. Using HashMap.containsKey() method, we will check if the key "E" is present in this hashMap. Since, the key "E" is not present in hashMap, containsKey() should return false.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,Integer> hashMap = new HashMap<>();
		hashMap.put("A",1);
		hashMap.put("B",2);
		hashMap.put("C",3);
		hashMap.put("D",4);

		boolean result = hashMap.containsKey("E");
		System.out.println("Does the HashMap contains key 'E' ? : " + result);
	}
}

Output

Does the HashMap contains key 'E' ? : false

3. containsKey(key) – When HashMap is null

In this example, we will initialize a HashMap hashMap with null. Calling HashMap.containsKey() method on null object should throw java.lang.NullPointerException.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,Integer> hashMap = null;

		boolean value1 = hashMap.containsKey("E");
		System.out.println("Does the HashMap contains key 'E' ? : " + value1);
	}
}

Output

Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:7)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashMap.containsKey() function, and also learnt how to use this function with the help of examples.