Home »
Java »
Java Programs
Java program to check whether a HashMap contains a specified value or not
Given a HashMap collection, we have to check whether it contains a specified value or not.
Submitted by Nidhi, on June 10, 2022
Problem statement
In this program, we will create a collection of key/value pair information using the HashMap collection. Then we will check whether a specified value exists in created HashMap or not using the containsValue() method.
Java program to check whether a HashMap contains a specified value or not
The source code to check whether a HashMap contains a specified value or not is given below. The given program is compiled and executed successfully.
// Java program to check whether a HashMap contains
// a specified value or not
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap < Integer, String > emp = new HashMap < > ();
emp.put(101, "Amit");
emp.put(102, "Arun");
emp.put(103, "Akas");
emp.put(104, "Ram");
emp.put(105, "Mohan");
if (emp.containsValue("Arun"))
System.out.println("Value 'Arun' is contained in 'emp' HashMap.");
else
System.out.println("Value 'Arun' is not contained in 'emp' HashMap.");
if (emp.containsValue("Anup"))
System.out.println("Value 'Anup' is contained in 'emp' HashMap.");
else
System.out.println("Value 'Anup' is not contained in 'emp' HashMap.");
}
}
Output
Value 'Arun' is contained in 'emp' HashMap.
Value 'Anup' is not contained in 'emp' HashMap.
Explanation
In the above program, we imported the "java.util.*" package to use the HashMap class. Here, we created a public class Main.
The Main class contains a main() method. The main() method is the entry point for the program. And, created an object of the HashMap class and store the employee information using the put() method. Then we checked whether the specified value exists in HashMap or not using the containsValue() method and printed the appropriate message.
Java HashMap Programs »