Tuesday 31 July 2012

Check if a particular value exists in Java HashMap example


This Java Example shows how to check if HashMap object contains a particular value using containsValue method of HashMap class.


import java.util.HashMap;

public class CheckParticularValueExistHashMapExample {

 public static void main(String[] args) {

  // create object of HashMap

  HashMap phoneBook = new HashMap();

  // add key value pairs to HashMap

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * To check whether a particular value exists in HashMap use boolean
   * containsValue(Object key) method of HashMap class. It returns true if
   * the value is mapped to one or more keys in the HashMap otherwise
   * false.
   **/

  boolean blnExists = phoneBook.containsValue("245745");

  System.out.println("Phone number '245745' exists in HashMap ? : "
    + blnExists);

 }
}



The output is:


Phone number '245745' exists in HashMap ? : true

No comments:

Post a Comment