.containsKey()
The .containsKey()
method is declared in the Map
interface and is primarily implemented in the HashMap
class. It is used to determine if a Map
object contains a specific key. The method returns true
if the key exists and false
otherwise.
Syntax
The .containsKey()
method can be called on a HashMap
instance like this:
hashMap.containsKey(key);
Parameters:
key
: The key to be checked. This can take on the form of any type ofObject
.
Return value:
The .containsKey()
method returns true
if the map contains the given key and false
otherwise.
Example 1: Basic Usage of .containsKey()
In this example, 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) {// Create a HashMapHashMap<String, Integer> basket = new HashMap<String, Integer>();// Add items to the HashMapbasket.put("Apples", 50);basket.put("Oranges", 30);// Check if the key "Apples" exists in the HashMapSystem.out.println("Basket contains Apples: " + basket.containsKey("Apples"));// Check if the key "Bananas" exists in the HashMapSystem.out.println("Basket contains Bananas: " + basket.containsKey("Bananas"));}}
Here is the output:
Basket contains Apples: trueBasket contains Bananas: false
Example 2: Conditional Logic with .containsKey()
In this example, the .containsKey()
method is used to check if the key "Germany"
exists in the map before adding it. This prevents overwriting existing data unintentionally:
import java.util.HashMap;public class Main {public static void main(String[] args) {// Create a HashMapHashMap<String, String> capitals = new HashMap<>();// Add items to the HashMapcapitals.put("USA", "Washington, D.C.");capitals.put("France", "Paris");// Create a stringString country = "Germany";// Check if the key "Germany" exists in the HashMapif (!capitals.containsKey(country)) {// Add the key "Germany" to the HashMapcapitals.put(country, "Berlin");System.out.println(country + " is added to the map.");} else {System.out.println(country + " is already in the map.");}}}
Here is the output:
Germany is added to the map.
Example 3: Using .containsKey()
in Loops
In this example, the .containsKey()
method is used in a loop to validate the presence of multiple keys in a map before attempting to retrieve their values:
import java.util.HashMap;public class Main {public static void main(String[] args) {// Create a HashMapHashMap<Integer, String> idMap = new HashMap<>();// Add items to the HashMapidMap.put(1, "Apple");idMap.put(2, "Banana");idMap.put(3, "Cherry");// Create an arrayint[] searchKeys = {2, 4};// Check if the keys in the array exist in the HashMapfor (int key : searchKeys) {if (idMap.containsKey(key)) {System.out.println("Key " + key + " maps to value: " + idMap.get(key));} else {System.out.println("Key " + key + " not found.");}}}}
In this example, the .get()
method is used to get the value of a specific key.
Here is the output:
Key 2 maps to value: BananaKey 4 not found.
Frequently Asked Questions
1. Can .containsKey()
be used with all map types?
Yes, all classes implementing the Map
interface (e.g., HashMap
, TreeMap
, LinkedHashMap
) support the .containsKey()
method.
2. What happens if I pass null
as a key to .containsKey()
?
If the map allows null
keys (like HashMap
), .containsKey()
will work. Otherwise, a NullPointerException
is thrown.
3. Is .containsKey()
time-efficient?
Yes. In a HashMap
, .containsKey()
has average time complexity of O(1), making it very efficient for key lookups.
Contribute to Docs
- 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.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours