Write a Java program to create a set view of the mappings contained in a map


This program creates a set view of a given HashMap object. The entrySet() method of the HashMap class returns a set view of the key-value pairs in the HashMap.

The program starts by creating a new HashMap object hash_map and populating it with key-value pairs using the put() method. Then it creates a set view of the HashMap by calling the entrySet() method and assigns it to a Set object named set.

Finally, it prints the contents of the set object using the println() method.

Note that the output of the println() method will be in the format of a Set object, which may not be in the same order as the original HashMap object.

Source Code

import java.util.*;  
public class Create_SetView
{  
	public static void main(String args[])
	{
		HashMap <Integer, String> hash_map = new HashMap <Integer, String> ();
		hash_map.put(1, "Red");
		hash_map.put(2, "Yellow");
		hash_map.put(3, "Black");
		hash_map.put(4, "Pink");
		hash_map.put(5, "Orange");
		hash_map.put(6, "Blue");
 
		Set set = hash_map.entrySet();// create set view
 
		System.out.println("Set values : " + set);// check set values
	}
}

Output

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