HashMap - Get Value from Key Example

In the last tutorial I have shared how to copy elements from one HashMap to another HashMap. In this tutorial we will see program to get value from key. The get(Object) method is used to get value from key.

Syntax:

public Value get(Object key) :

According to Oracle docs,
1. it returns the value to which specified key is matched or
2. it returns null if  the map contains no mapping for the key.

Program to Get Value from Key 



import java.util.*;

 public class HashMapGetExample {
    public static void main(String args[]) {
        
    // Creating a HashMap of Integer keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
    hashmap.put(1, "Value1");
    hashmap.put(2, "Value2");
    hashmap.put(3, "Value3");
    hashmap.put(4, "Value4");
    hashmap.put(5, "Value5");
    // Getting values from HashMap
     String val = hashmap.get(3);
     System.out.println("The Value mapped to Key 3 is:"+ val);
 
     /* Here Key "7" is not mapped to any value so this 
      * operation returns null.
      */
     String val2 = hashmap.get(7);
     System.out.println("The Value mapped to Key 7 is:s"+ val2);
  }
}


Output
The Value mapped to Key 3 is:Value3
The Value mapped to Key 7 is:null
You must use containsKey() method for checking the existence of a Key in HashMap not the get() method.It is because a return value of null does not necessarily indicate that the map contains no mapping for the key,its also possible that the map explicitly maps the key to null.




About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry