Write a Java program to get a set view of the keys contained in this map


This program uses a HashMap to store key-value pairs of Integer and String data types. It then retrieves a Set view of the keys in the HashMap using the keySet() method, and prints the Set view to the console.

  • A HashMap hash_map is created with Integer keys and String values.
  • Key-value pairs are added to the HashMap using the put() method.
  • The keySet() method is used to retrieve a Set view of the keys in the HashMap, which is assigned to the keyset variable.
  • The Set view of the keys is printed to the console using the println() method.

Source Code

import java.util.*;  
public class GetSet_ViewKeys
{  
	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");
 
		Set keyset = hash_map.keySet();
		System.out.println("Key set values are : " + keyset);  
	}
}

Output

Key set values are : [1, 2, 3, 4, 5, 6, 7]