Introduction
In this lab, you will learn how to check if a specific value exists within a HashMap in Java. We will explore the convenient containsValue() method provided by the HashMap class, which efficiently determines if a value is present.
Furthermore, we will examine how to manually iterate through the map's values to perform the check, providing an alternative approach. Finally, we will discuss how to handle null values when checking for their presence within the map.
Use containsValue() for Value Check
In this step, we will explore how to check if a specific value exists within a HashMap in Java. HashMap is a very useful data structure that stores key-value pairs. Sometimes, you might need to know if a particular value is present in the map, regardless of its key.
Java's HashMap class provides a convenient method called containsValue() for this purpose. This method takes a value as an argument and returns true if the map contains at least one key-value mapping where the value is equal to the specified value. Otherwise, it returns false.
Let's create a simple Java program to demonstrate how to use containsValue().
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.Replace the entire contents of the file with the following code:
import java.util.HashMap; public class HelloJava { public static void main(String[] args) { // Create a HashMap HashMap<String, Integer> ages = new HashMap<>(); // Add some key-value pairs ages.put("Alice", 30); ages.put("Bob", 25); ages.put("Charlie", 35); ages.put("David", 25); // Another person with age 25 // Check if a specific value exists int valueToCheck = 25; boolean contains25 = ages.containsValue(valueToCheck); System.out.println("Does the map contain the value " + valueToCheck + "? " + contains25); valueToCheck = 40; boolean contains40 = ages.containsValue(valueToCheck); System.out.println("Does the map contain the value " + valueToCheck + "? " + contains40); } }Let's look at the new parts of this code:
import java.util.HashMap;: This line imports theHashMapclass, which we need to use.HashMap<String, Integer> ages = new HashMap<>();: This line creates a newHashMapwhere keys areString(like names) and values areInteger(like ages).ages.put("Alice", 30);and similar lines: These lines add key-value pairs to theHashMap.int valueToCheck = 25;: This declares an integer variablevalueToCheckand assigns it the value 25.boolean contains25 = ages.containsValue(valueToCheck);: This is where we use thecontainsValue()method. It checks if the value stored invalueToCheck(which is 25) exists anywhere in theagesmap's values. The result (trueorfalse) is stored in thecontains25boolean variable.System.out.println(...): These lines print the results to the console.
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaIf there are no errors, a
HelloJava.classfile will be created.Run the compiled program:
java HelloJavaYou should see output indicating whether the values 25 and 40 are present in the map.
Does the map contain the value 25? true Does the map contain the value 40? false
This demonstrates how easily you can check for the existence of a value in a HashMap using the containsValue() method.
Loop Through Values Manually
In the previous step, we used the built-in containsValue() method to check for a value. While this is the most efficient way, it's also helpful to understand how you could manually check for a value by iterating through all the values in the HashMap. This process involves getting a collection of all the values and then looping through them one by one.
Java's HashMap provides a method called values() which returns a Collection view of the values contained in the map. We can then iterate over this Collection using a loop.
Let's modify our program to manually check if the value 25 exists by looping through the values.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
import java.util.HashMap; import java.util.Collection; public class HelloJava { public static void main(String[] args) { // Create a HashMap HashMap<String, Integer> ages = new HashMap<>(); // Add some key-value pairs ages.put("Alice", 30); ages.put("Bob", 25); ages.put("Charlie", 35); ages.put("David", 25); // Another person with age 25 // Get a collection of all values Collection<Integer> allAges = ages.values(); // Manually check if a specific value exists by looping int valueToCheck = 25; boolean foundManually = false; for (Integer age : allAges) { if (age.equals(valueToCheck)) { foundManually = true; break; // Exit the loop once the value is found } } System.out.println("Does the map contain the value " + valueToCheck + " (manual check)? " + foundManually); valueToCheck = 40; foundManually = false; // Reset for the next check for (Integer age : allAges) { if (age.equals(valueToCheck)) { foundManually = true; break; } } System.out.println("Does the map contain the value " + valueToCheck + " (manual check)? " + foundManually); } }Here's what's new or changed:
import java.util.Collection;: We import theCollectioninterface becauseages.values()returns aCollection.Collection<Integer> allAges = ages.values();: This line gets aCollectioncontaining all the integer values (ages) from ouragesmap.for (Integer age : allAges): This is an enhanced for loop (also known as a for-each loop) that iterates through eachIntegerelement in theallAgescollection. In each iteration, the current value is assigned to theagevariable.if (age.equals(valueToCheck)): Inside the loop, we compare the currentagewith thevalueToCheck. We useequals()for comparing objects (likeInteger), which is generally safer than using==for objects.foundManually = true;: If a match is found, we setfoundManuallytotrue.break;: This statement exits the loop immediately once the value is found, making the check more efficient.
Save the file.
Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaThe output should be the same as in the previous step, confirming that our manual check works correctly.
Does the map contain the value 25 (manual check)? true Does the map contain the value 40 (manual check)? false
While manually looping works, using containsValue() is generally preferred because it's more concise and often optimized for performance within the Java library. However, understanding how to iterate through values is a fundamental skill that will be useful in many other scenarios.
Handle Null Values
In Java, null is a special value that means "no object". It's important to understand how HashMap handles null values and how containsValue() behaves when dealing with null.
A HashMap in Java can store null values. You can add a mapping where the value is null.
Let's modify our program to include a null value and see how containsValue() works with it.
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 HashMap<String, Integer> ages = new HashMap<>(); // Add some key-value pairs, including a null value ages.put("Alice", 30); ages.put("Bob", 25); ages.put("Charlie", null); // Charlie's age is unknown (null) ages.put("David", 25); // Check if a specific value exists, including null int valueToCheck = 25; boolean contains25 = ages.containsValue(valueToCheck); System.out.println("Does the map contain the value " + valueToCheck + "? " + contains25); Integer nullValue = null; boolean containsNull = ages.containsValue(nullValue); System.out.println("Does the map contain the value null? " + containsNull); valueToCheck = 40; boolean contains40 = ages.containsValue(valueToCheck); System.out.println("Does the map contain the value " + valueToCheck + "? " + contains40); } }Here's the key change:
ages.put("Charlie", null);: We've added a mapping where the key "Charlie" is associated with anullvalue.Integer nullValue = null;: We create anIntegervariable and assign it the valuenull.boolean containsNull = ages.containsValue(nullValue);: We usecontainsValue()to check if the map contains thenullvalue.
Save the file.
Compile the program:
javac HelloJava.javaRun the program:
java HelloJavaObserve the output, especially the line checking for
null.Does the map contain the value 25? true Does the map contain the value null? true Does the map contain the value 40? false
As you can see, containsValue() correctly identifies that the HashMap contains the null value because we explicitly added it. This confirms that HashMap can store null values and containsValue() can be used to check for their presence.
Handling null values is an important aspect of Java programming. Always be mindful of whether your data structures might contain null and how your code will behave in such cases.
Summary
In this lab, we learned how to check if a HashMap contains a specific value in Java. The primary method explored was containsValue(), which provides a straightforward way to determine the presence of a value within the map. We saw how to use this method with a simple example, demonstrating its return value based on whether the target value exists in the map.
We also explored alternative methods for checking value existence, such as manually iterating through the map's values. Additionally, the lab covered how to handle null values when checking for their presence in the map, ensuring a comprehensive understanding of value checking in HashMap.



