Write a Java program to get the value of a specified key in a map


The code you provided is correct and it will print the value associated with key 4 in the hash map, which is "White". Here's the explanation:

  • First, you created a hash map object called hash_map and added several key-value pairs using the put method.
  • Then, you retrieved the value associated with key 4 using the get method and assigned it to the variable val.
  • Finally, you printed the value of val using the println method.

Source Code

import java.util.*;  
public class GetValue
{  
	public static void main(String args[])
	{  
		HashMap<Integer,String> hash_map = new HashMap<Integer,String>();  
		hash_map.put(1, "Blue");
		hash_map.put(2, "Green");
		hash_map.put(3, "Pink");
		hash_map.put(4, "White");
		hash_map.put(5, "Red");
		hash_map.put(6, "Black");
		hash_map.put(7, "Orange");
		String val=(String)hash_map.get(4);
		System.out.println("Value for key 4 is: " + val);
	}
}

Output

Set values : [1=Red, 2=Yellow, 3=Black, 4=Pink, 5=Orange, 6=Blue]

C:\Users\tutor\Desktop\OFFICE_WORK\WEBSITE_PROGRAM\HASHMAP_PENDING>java 10_GetValue.java
Value for key 4 is: White