Java HashMap is an implementation of the Map interface which maps a Value to a Key which essentially forms an associative pair wherein we can call a Value based on the Key. Java HashMap provides a lot of advantages such as allowing different data types for the Key and Value which makes this data structure more inclusive and versatile. It also allows null for the Key and the Value given that one of the two forming a pair is not null.
The different approaches to check for the existence of a particular Value in a Java HashMap are:
- Using the built in containsValue() method of the HashMap class
- Creating a map from the entries of the HashMap and then iterating through the Values
- Creating an ArrayList from the Values of the HashMap and then iterating through this list
Approach 1 :
This approach provides a fairly simple and efficient method to check for the existence of a Value in a HashMap using the containsValue() predefined method which returns a boolean value.
Parameters: The method takes just one parameter Value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map.
Return Value: The method returns boolean true if the mapping of the value is detected else false.
- Declare a method with return type boolean to check for the existence of the value.
- Initialize a HashMap describing the data types for the Key as well as the Values.
- Fill this HashMap with Key-Value pairs using the built in put() method of the HashMap class.
- Declare a boolean variable to store the result of the containsValue() method.
Approach 2 :
Using this approach, we create a Map from all the entries of the HashMap, Keys and Values included and then iterate only through the Values to check for the specific one.
- Repeat steps 1 through 3 as described in the first approach to create a HashMap.
- Then create a Map using a for each loop and the predefined entrySet() method of the HashMap.
- Iterate through the values in the Map using the predefined getValue() method of the Map class.
- At each iteration, compare the Value with the specified Value and return the corresponding result.
Approach 3 :
Under the third approach, we create an ArrayList from the values of the HashMap and iterate through the entire list to check for the specific value mentioned.
- Repeat steps 1 through 3 to create a HashMap.
- Next, create an ArrayList of the same data type as the values in the HashMap.
- In the next step we declare an iterator to iterate through the entire ArrayList till it finds the specific value.
- Using a while loop iterate through the values stored in the ArrayList and in each iteration checking with the specified value.
- Return the corresponding result as a boolean value.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.