Write a Java program to associate the specified value with the specified key in a HashMap


This Java program creates a HashMap with integer keys and string values, and adds five key-value pairs to the map using the put() method. It then iterates over the entries in the map using a for-each loop and the entrySet() method, and prints out each key-value pair to the console using the getKey() and getValue() methods of the Map.Entry interface.

Source Code

import java.util.*;  
public class Specified_Value
{  
	public static void main(String args[])
	{  
		HashMap<Integer,String> hash_map = new HashMap<Integer,String>();  
		hash_map.put(1, "Pink");
		hash_map.put(2, "Green");
		hash_map.put(3, "Black");
		hash_map.put(4, "White");
		hash_map.put(5, "Blue");
		for(Map.Entry x:hash_map.entrySet())
		{  
			System.out.println(x.getKey()+" "+x.getValue());  
		}  
	}  
}

Output

1 Pink
2 Green
3 Black
4 White
5 Blue