tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collection > Maps > Contains

Contains 

The following example shows how to check whether a specified key or value exists in the Map. HashMap and Hashtable are two implementations of Map interface. Hashtable is synchronized where as HashMap is not. Map provides the following APIs,

public boolean containsKey(Object paramObject);
 - Returns true if the Map contains specified key otherwise returns false. 
 
public boolean containsValue(Object paramObject);
 - Returns true if the Map contains specified value otherwise returns false.  


File Name  :  
com/bethecoder/tutorials/utils/maps/ContainsTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.maps;

import java.util.HashMap;
import java.util.Map;

public class ContainsTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    Map<Integer, String> numMap = new HashMap<Integer, String>();
    numMap.put(new Integer(1)"ONE");
    numMap.put(new Integer(2)"TWO");
    numMap.put(new Integer(3)"THREE");
    
    System.out.println(numMap);
    System.out.println();
    
    //Check for key
    System.out.println("Map contains key '1' : " + numMap.containsKey(new Integer(1)));
    System.out.println("Map contains key '6' : " + numMap.containsKey(new Integer(6)));
    System.out.println();
    
    //Check for value
    System.out.println("Map contains value 'TWO' : " + numMap.containsValue("TWO"));
    System.out.println("Map contains value 'SIX' : " + numMap.containsValue("SIX"));
  }

}
   

It gives the following output,
{1=ONE, 2=TWO, 3=THREE}

Map contains key '1' : true
Map contains key '6' : false

Map contains value 'TWO' : true
Map contains value 'SIX' : false



 
  


  
bl  br