beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Check if a particular value exists in HashMap example

By Chaitanya Singh | Filed Under: Java Collections

In this example we are checking whether a particular value exists in HashMap or not. We will be using containsValue() method of HashMap class to perform this check:

public boolean containsValue(Object value): Returns true if this map maps one or more keys to the specified value.

Complete Code:

Here we have a HashMap of integer keys and String values, we are checking whether a particular String is mapped to any of the key of HashMap.

import java.util.HashMap;

public class CheckValueExample {
 
 public static void main(String[] args) {
 
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
 
    // Adding Key and Value pairs to HashMap
    hashmap.put(11,"Chaitanya");
    hashmap.put(22,"Pratap");
    hashmap.put(33,"Singh");
    hashmap.put(44,"Rajesh");
    hashmap.put(55,"Kate");
 
    // Checking Value Existence
    boolean flag = hashmap.containsValue("Singh");
    System.out.println("String Singh exists in HashMap? : " + flag);
 }
}

Output:

String Singh exists in HashMap? : true

Enjoyed this post? Try these related posts

  1. How to convert Vector to String array in java
  2. Java Iterator with examples
  3. Java – LinkedList ListIterator example
  4. Difference between ArrayList and HashMap in Java
  5. How to convert ArrayList to string array in java
  6. How to get the last element of Arraylist?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap