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. Queue Interface in Java Collections
  2. How to get the last element of Arraylist?
  3. How to Set Vector size example
  4. ArrayList in java with example programs – Collections Framework
  5. How to synchronize ArrayList in java with example
  6. Java – Remove element from a specific index in LinkedList example

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