HashMap search

In this chapter you will learn:

  1. How to check key existence in a HashMap
  2. How to check value existence in a HashMap

Check key existence

containsKey(Object key) checks to see if the HashMap has that key

import java.util.HashMap;
/*from  j a v  a2 s  .c o m*/
public class Main {
  public static void main(String[] args) {
    HashMap<String, String> hMap = new HashMap<String, String>();

    hMap.put("1", "One");
    hMap.put("2", "Two");
    hMap.put("3", "Three");

    boolean blnExists = hMap.containsKey("3");
    System.out.println("3 exists in HashMap ? : " + blnExists);
  }
}

Value existence

containsValue(Object value) checks if the HashMap has that value
import java.util.HashMap;
import java.util.Map;
/*  jav  a2s  .  co m*/
public class Main {
  public static void main(String[] a) {
    Map<String,String> map = new HashMap<String,String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println(map.containsKey("key1"));
    System.out.println(map.containsValue("value2"));
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to clone a HashMap
Home » Java Tutorial » Map
Map interface
Map element adding
Map.Entry class
Map key
Map value
Map key/value search
Map delete/remove
Map comparison
HashMap Class
HashMap search
HashMap clone
TreeMap
TreeMap key
TreeMap head sub map
TreeMap tail sub map
TreeMap sub map
NavigableMap
NavigableMap key
NavigableMap key-value pair
LinkedHashMap Class
IdentityHashMap
SortedMap