Write a Java program to get keys from a HashMap collection


This Java program demonstrates how to get the keys of a HashMap collection using the keySet() method. Here is a step-by-step explanation of the program:

  • First, we import the java.util.* package, which includes the HashMap and Set classes that we'll be using.
  • We define a new class called Get_Keys.
  • Inside the main method, we create a new HashMap object called stu that maps integer keys to string values.
  • We use the put method to add key-value pairs to the stu HashMap.
  • We create a new Set object called keys and use the keySet() method to retrieve the set of keys from the stu HashMap. The keySet() method returns a view of the keys in the HashMap.
  • We use a for loop to iterate through the set of keys in keys.
  • Inside the loop, we use the println() method to print each key to the console.
  • Finally, we close the main method and the Get_Keys class.

Source Code

import java.util.*;
public class Get_Keys
{
	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(104, "Ramesh");
		stu.put(105, "Joes");
		stu.put(106, "Abi");
		stu.put(107, "John");
		stu.put(108, "Vijay");
		stu.put(109, "Suga");
		stu.put(110, "Siva");
		Set < Integer > keys = stu.keySet();
 
		System.out.println("Keys from a HashMap Collection ..");
		for (Integer key: keys)
		{
			System.out.println(key);
		}
	}
}

Output

Keys from a HashMap Collection ..
101
102
103
104
105
106
107
108
109
110