Introduction
In this lab, you will learn how to effectively check if a specific key exists within a Java Map. This is a crucial skill for preventing errors and ensuring robust map operations.
We will explore the fundamental containsKey() method for checking key presence, demonstrate its usage with different key types, and address how to handle null keys, providing a comprehensive understanding of key checking in Java maps.
Use containsKey() for Key Check
In this step, we will learn how to check if a specific key exists in a HashMap using the containsKey() method. This is a fundamental operation when working with maps, allowing you to avoid errors that might occur if you try to access a key that doesn't exist.
A HashMap is a data structure in Java that stores key-value pairs. Think of it like a dictionary where each word (the key) has a definition (the value). The containsKey() method is like asking the dictionary, "Do you have an entry for this specific word?"
Let's create a simple Java program to demonstrate how to use containsKey().
Open the
HelloJava.javafile in the WebIDE editor. If you completed the previous lab, this file should already exist in your~/projectdirectory.Replace the existing code in
HelloJava.javawith the following code:import java.util.HashMap; public class HelloJava { public static void main(String[] args) { // Create a HashMap HashMap<String, String> userMap = new HashMap<>(); // Add some key-value pairs userMap.put("alice", "Alice Smith"); userMap.put("bob", "Bob Johnson"); userMap.put("charlie", "Charlie Brown"); // Check if a key exists using containsKey() String keyToCheck1 = "alice"; String keyToCheck2 = "david"; System.out.println("Checking for key: " + keyToCheck1); if (userMap.containsKey(keyToCheck1)) { System.out.println("Key '" + keyToCheck1 + "' exists in the map."); } else { System.out.println("Key '" + keyToCheck1 + "' does not exist in the map."); } System.out.println("\nChecking for key: " + keyToCheck2); if (userMap.containsKey(keyToCheck2)) { System.out.println("Key '" + keyToCheck2 + "' exists in the map."); } else { System.out.println("Key '" + keyToCheck2 + "' does not exist in the map."); } } }Let's look at the new parts of this code:
import java.util.HashMap;: This line imports theHashMapclass, which we need to use HashMaps.HashMap<String, String> userMap = new HashMap<>();: This line creates a newHashMapwhere both the keys and values areStringtypes.userMap.put("alice", "Alice Smith");: This adds a key-value pair to the map. The key is"alice"and the value is"Alice Smith".userMap.containsKey(keyToCheck1): This is the core of this step. ThecontainsKey()method takes a key as an argument and returnstrueif the key is found in the map, andfalseotherwise.
Save the
HelloJava.javafile (Ctrl+S or Cmd+S).Now, compile the program using the
javaccommand in the terminal:javac HelloJava.javaIf there are no errors, you will not see any output.
Finally, run the compiled program using the
javacommand:java HelloJavaYou should see output similar to this:
Checking for key: alice Key 'alice' exists in the map. Checking for key: david Key 'david' does not exist in the map.
This output confirms that containsKey() correctly identified whether the keys "alice" and "david" were present in our userMap.
Test with Different Key Types
In the previous step, we used String keys in our HashMap. However, HashMap can use various data types as keys, as long as they are objects (primitive types like int, char, etc., are automatically "boxed" into their corresponding object wrappers like Integer, Character).
In this step, we will explore using different data types as keys in a HashMap and see how containsKey() works with them.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
import java.util.HashMap; public class HelloJava { public static void main(String[] args) { // Create a HashMap with Integer keys and String values HashMap<Integer, String> studentMap = new HashMap<>(); // Add some key-value pairs studentMap.put(101, "Alice Smith"); studentMap.put(102, "Bob Johnson"); studentMap.put(103, "Charlie Brown"); // Check for keys using containsKey() with Integer keys Integer keyToCheck1 = 101; Integer keyToCheck2 = 200; // A key that does not exist System.out.println("Checking for key: " + keyToCheck1); if (studentMap.containsKey(keyToCheck1)) { System.out.println("Key '" + keyToCheck1 + "' exists in the map."); } else { System.out.println("Key '" + keyToCheck1 + "' does not exist in the map."); } System.out.println("\nChecking for key: " + keyToCheck2); if (studentMap.containsKey(keyToCheck2)) { System.out.println("Key '" + keyToCheck2 + "' exists in the map."); } else { System.out.println("Key '" + keyToCheck2 + "' does not exist in the map."); } // You can also use primitive int directly, Java will auto-box it int primitiveKey = 102; System.out.println("\nChecking for primitive key: " + primitiveKey); if (studentMap.containsKey(primitiveKey)) { System.out.println("Key '" + primitiveKey + "' exists in the map."); } else { System.out.println("Key '" + primitiveKey + "' does not exist in the map."); } } }In this code, we've created a
HashMapwhere the keys areIntegerobjects (representing student IDs) and the values areStringobjects (representing student names). We then usecontainsKey()with bothIntegerobjects and a primitiveintto show that Java handles the conversion (auto-boxing) for you.Save the
HelloJava.javafile.Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaYou should see output similar to this:
Checking for key: 101 Key '101' exists in the map. Checking for key: 200 Key '200' does not exist in the map. Checking for primitive key: 102 Key '102' exists in the map.
This demonstrates that containsKey() works correctly with Integer keys, and that Java's auto-boxing feature allows you to use primitive int values directly when checking for keys in a HashMap<Integer, ...>.
Handle Null Keys
In Java's HashMap, you can actually use null as a key, but only one null key is allowed. It's important to understand how containsKey() behaves when dealing with null keys.
In this step, we will modify our program to include a null key and then use containsKey() to check for its presence.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
import java.util.HashMap; public class HelloJava { public static void main(String[] args) { // Create a HashMap that allows null keys HashMap<String, String> statusMap = new HashMap<>(); // Add some key-value pairs, including a null key statusMap.put("active", "User is currently online"); statusMap.put("inactive", "User is offline"); statusMap.put(null, "User status is unknown"); // Adding a null key // Check for keys using containsKey(), including null String keyToCheck1 = "active"; String keyToCheck2 = "pending"; // A key that does not exist String keyToCheck3 = null; // The null key System.out.println("Checking for key: " + keyToCheck1); if (statusMap.containsKey(keyToCheck1)) { System.out.println("Key '" + keyToCheck1 + "' exists in the map."); } else { System.out.println("Key '" + keyToCheck1 + "' does not exist in the map."); } System.out.println("\nChecking for key: " + keyToCheck2); if (statusMap.containsKey(keyToCheck2)) { System.out.println("Key '" + keyToCheck2 + "' exists in the map."); } else { System.out.println("Key '" + keyToCheck2 + "' does not exist in the map."); } System.out.println("\nChecking for null key:"); if (statusMap.containsKey(keyToCheck3)) { System.out.println("Null key exists in the map."); } else { System.out.println("Null key does not exist in the map."); } } }Here, we've created a
HashMapwithStringkeys and values. We then explicitly add anullkey usingstatusMap.put(null, "User status is unknown");. Finally, we usecontainsKey(null)to check if thenullkey is present.Save the
HelloJava.javafile.Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaYou should see output similar to this:
Checking for key: active Key 'active' exists in the map. Checking for key: pending Key 'pending' does not exist in the map. Checking for null key: Null key exists in the map.
This output confirms that containsKey() correctly identifies the presence of the null key in the HashMap. While using null keys is possible, it's often recommended to avoid them if possible to make your code clearer and prevent potential NullPointerException issues in other parts of your program.
Summary
In this lab, we learned how to check if a specific key exists in a Java HashMap using the containsKey() method. This fundamental operation is crucial for preventing errors when accessing map elements. We practiced using containsKey() with string keys and observed how it correctly identifies existing and non-existing keys.



