Java HashMap containsValue(Object value) Example

The containsKey(Object key) method of java.util.HashMap class returns true if this map contains a mapping for the specified key where as containsValue(Object value) method returns true if this map maps one or more keys to the specified value.

Signature

public boolean containsValue(Object value)

This method returns true if this map maps one or more keys to the specified value.

Example

The following example shows the usage of java.util.HashMap.containsValue(value) method.

import java.util.HashMap;

public class ContainsValueMethodHashMapExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String>  hashMap1 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
        
        //Check if the hashmap1 contains value "Element3"
        System.out.println("Does \"hashMap1\" contains value \"Element3\" : "+hashMap1.containsValue("Element3"));
    }
}

Output

Does "hashMap1" contains value "Element3" : true

Leave a Reply

Your email address will not be published. Required fields are marked *