Write a Java Program to get value from HashMap when the key is provided


The program first creates a HashMap object h of type HashMap. It then adds several key-value pairs to the HashMap using the put method.

After printing the initial state of the HashMap using a for-each loop to iterate over the entries, the program uses a for loop to retrieve the values mapped to the keys 1 through 7 using the get method. For each key, the program prints the value returned by the get method.

Note that since the HashMap does not contain a key-value pair for the key 7, the program will print null when retrieving the value for this key.

Source Code

import java.util.*;
class GetValues
{ 
	public static void main(String[] args)
	{
		HashMap<Integer,String> h =new HashMap<>();
		h.put(1,"Sam");
		h.put(6,"Sathish");
		h.put(3,"Pooja");
		h.put(4,"Ram"); 
		h.put(6,"Kumar");
		System.out.println("Given HashMap..");
		for(Map.Entry e : h.entrySet())
		{
			System.out.println("Key : "+ e.getKey()+" || Value : "+e.getValue());
		}
		for(int i=1;i<=7;i++)
		{			
			System.out.println("Value mapped to Key "+i+" is : "+ h.get(i));
		}
	}
}

Output

Given HashMap..
Key : 1 || Value : Sam
Key : 3 || Value : Pooja
Key : 4 || Value : Ram
Key : 6 || Value : Kumar
Value mapped to Key 1 is : Sam
Value mapped to Key 2 is : null
Value mapped to Key 3 is : Pooja
Value mapped to Key 4 is : Ram
Value mapped to Key 5 is : null
Value mapped to Key 6 is : Kumar
Value mapped to Key 7 is : null