Map key/value search

In this chapter you will learn:

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

We can check if a key is inside a Map. containsKey returns true if a key is there, it returns false if a key is not there.

import java.util.HashMap;
import java.util.Map;
//from j a  v a  2 s  .  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.get("key2"));
    System.out.println(map.containsKey("key2"));
    System.out.println(map.containsKey("key4"));
  }
}

The code above generates the following result.

Value existence in a Map

To see if a value is contained in a Map use containsValue.

import java.util.HashMap;
import java.util.Map;
/*from  j  a va2s.c  o  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"));
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to remove key and value pair
  2. How to remove all key and value pair from a Map
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