Check if Particular Value Exists in Java HashMap
Last Updated :
30 Jul, 2021
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.
Syntax:
Hash_Map.containsValue(Object 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.
Algorithm :
- 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.
Code :
Java
// java program to check if a particular
// value exists in a HashMap
import java.util.*;
class GFG {
// declaring the method to return
// if the value is present or not
// the parameter valueToBeChecked
// represents the value to be checked
boolean checkForValue(int valueToBeChecked)
{
// initializing the HashMap
HashMap<String, Integer> hashMap = new HashMap<>();
// filling the HashMap with
// key value pairs
hashMap.put("key1", 1);
hashMap.put("key2", 2);
hashMap.put("key3", 3);
hashMap.put("key4", 4);
// declaring the variable to store
// the result
// calling the containsValue() method
boolean result
= hashMap.containsValue(valueToBeChecked);
// returning the result
return result;
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
// displaying and calling the
// checkForValue() method
System.out.println(ob.checkForValue(10));
}
}
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.
Algorithm :
- 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.
Code :
Java
// java program to check if a particular
// value exists in HashMap
import java.util.*;
class GFG {
// declaring the method
// the parameter is the variable which
// stores the value to be checked
boolean checkForValue(int valueToBeChecked)
{
// initializing the HashMap
HashMap<String, Integer> hashMap = new HashMap<>();
// filling up the HashMap with
// Key-Value pairs
hashMap.put("key1", 1);
hashMap.put("key2", 2);
hashMap.put("key3", 3);
hashMap.put("key4", 4);
// for each loop
// all the entries in the HashMap are
// stored in the Map
for (Map.Entry<String, Integer> mapEntries :
hashMap.entrySet()) {
// fetching the values of the HashMap
// one at a time and comparing with
// the value to be checked
if (mapEntries.getValue() == valueToBeChecked)
return true;
}
return false;
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
// displaying and calling the
// checkForValue() method
System.out.println(ob.checkForValue(2));
}
}
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.
Algorithm :
- 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.
Code :
Java
// java program to check if a particular
// key exists in a HashMap
import java.util.*;
class GFG {
// declaring the method
// the parameter specifies the value to
// be checked
boolean checkForValue(int valueToBeChecked)
{
// initializing the HashMap
HashMap<String, Integer> hashMap = new HashMap<>();
// filling up the HashMap with
// Key-Value pairs
hashMap.put("key1", 1);
hashMap.put("key2", 2);
hashMap.put("key3", 3);
hashMap.put("key4", 4);
// declaring an ArrayList of type
// Integer from the values of the
// HashMap using the predefined
// values() method of the HashMap class
ArrayList<Integer> listOfValues
= new ArrayList<>(hashMap.values());
// declaring the iterator
Iterator<Integer> itr = listOfValues.iterator();
// iterating through the list
while (itr.hasNext()) {
// comparing each value with the
// one specified
if (itr.next() == valueToBeChecked)
return true;
}
return false;
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
// displaying and calling the
// checkForValue() method
System.out.println(ob.checkForValue(0));
}
}
Similar Reads
Check if Particular Key Exists in Java HashMap HashMap in Java is the realization of the Hash Table data structure of sorts. It is composed of Key and Value pairs which are symbolically represented as <K,V> where K stands for Key and V for Value. It is an implementation of the Maps Interface and is advantageous in the ways that it provides
5 min read
How to Check if LinkedHashMap Contains a value in Java? LinkedHashMap is a predefined class in Java which is similar to HashMap, contains key and its respective value unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to check if LinkedHashMap contains any value in java. to check we have to iterate through our LinkedHashMap and if
3 min read
Checking if Element Exists in LinkedHashSet in Java The Java.util.LinkedHashSet.contains() method is used to check whether a specific element is present in the LinkedHashSet or not. So basically it is used to check if a Set contains any particular element. The contains a method of the LinkedHashSet class returns true if the specified element is found
1 min read
Traverse Through a HashMap in Java HashMap stores the data in (Key, Value) pairs, and you can access them by an index of another type. HashMap class implements Map interface which allows us to store key. hashMap is a part of the java collections framework been up since Java 1.2. It internally uses hashing technique which is pretty fa
4 min read
Java Program to Check if the TreeMap is Empty The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Approaches: Using the isEmpty() methodU
3 min read
How to Check if LinkedHashMap is Empty in Java? The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements
2 min read
Java Program to Sort a HashMap by Keys and Values HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate
3 min read
Getting Set View of Keys from HashMap in Java The HashMap class of Java provides the functionality of the hash table data structure. This class is found in the java.util package. It implements the Map interface. It stores elements in (Key, Value) pairs and you can access them by an index of another type (e.g. Integer/String). Here, keys are use
2 min read
Java Program to Implement IdentityHashMap API The IdentityHashMap implements Map interface using Hashtable, using reference-equality in place of object-equality when comparing keys (and values). This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Mapâs general contract
6 min read
Java Program to Implement ConcurrentHashMap API ConcurrentHashMap class obeys the same functional specification as HashTable and includes all the versions of methods corresponding to each method of a HashTable. A HashTable supports the full concurrency of retrievals and adjustable concurrency for updates. All the operations of ConcurrentHashMap a
6 min read