- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to check if a given value exists in a HashMap
Use the containsValue() method to check if a given value exists or not in a HashMap.
First, let us create a HashMap and add some elements −
HashMap hm = new HashMap(); // Put elements to the map hm.put("Bag", new Integer(1100)); hm.put("Sunglasses", new Integer(2000)); hm.put("Frames", new Integer(800)); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600));
Now let us check whether a given value exist or not. Here, we are checking for the value “800” −
hm.containsValue(800);
The following is an example to check if a given value exists in a HashMap −
Example
import java.util.*; public class Demo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("Bag", new Integer(1100)); hm.put("Sunglasses", new Integer(2000)); hm.put("Frames", new Integer(800)); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600)); // Get a set of the entries Set set = hm.entrySet(); System.out.println("Elements in HashMap..."); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); System.out.println("Does key Bag exist in the HashMap = "+hm.containsKey("Bag")); System.out.println("Does value 800 exist in the HashMap = "+hm.containsValue(800)); } }
Output
Elements in HashMap... Frames: 800 Belt: 600 Wallet: 700 Bag: 1100 Sunglasses: 2000 Does key Bag exist in the HashMap = true Does value 800 exist in the HashMap = true
- Related Articles
- Check if a given key exists in Java HashMap
- Java Program to check if a particular value exists in TreeMap
- Check if a particular value exists in Java LinkedHashMap
- Check if a particular value exists in Java TreeSet
- Java Program to check if a particular element exists in HashSet
- Java Program to check if a particular key exists in TreeMap
- C# Program to Check if Value exists in Hashtable
- Java Program to Check if An Array Contains a Given Value
- Java Program to remove a key from a HashMap only if it is associated with a given value
- Check if a HashMap is empty in Java
- Check if a file exists in Java\n
- Check if a value exists in a column in a MySQL table?
- Check if value exists for a field in a MongoDB document?
- How to check if a given key already exists in a Python dictionary?
- Check if a particular key exists in Java LinkedHashMap

Advertisements