Java HashMap get(Object key) Example

The get(Object key) method of java.util.HashMap class returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Signature

public V get(Object key)

This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. A return value of null does not necessarily indicate that the map contains no mapping for the key, it’s also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Example

The following example shows the usage of java.util.HashMap.get(key) method.

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

public class GetMethodTreeSetExample 
{
    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");
        
        //get the value of key 3
        String val = (String)hashMap1.get(2)
        System.out.println("Value of Key \"2\" is : "+val);
    }
}

Output

Value of Key 2 : Element2

Leave a Reply

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