Write a Java program to get the value based on the key from a HashMap collection


The program creates a HashMap called stu which stores Integer keys and String values. The put method is used to add key-value pairs to the map. The program then uses the get method to retrieve values from the map based on the key. The output of the program shows the values associated with keys 101, 103, and 105.

Source Code

import java.util.*;
public class GetValue_BasedKey
{
	public static void main(String[] args)
	{
		HashMap <Integer,String> stu = new HashMap <>();
		stu.put(101, "Kim");
		stu.put(102, "Arun");
		stu.put(103, "Deepika");
		stu.put(105, "Joes");
		stu.put(107, "John");
		stu.put(108, "Vijay");
 
		System.out.println("Value for 101 : " + stu.get(101));
		System.out.println("Value for 103 : " + stu.get(103));
		System.out.println("Value for 105 : " + stu.get(105));
	}
}

Output

Value for 101 : Kim
Value for 103 : Deepika
Value for 105 : Joes