Home »
Java »
Java Programs
Java program to get keys from a HashMap collection
Given a HashMap collection, we have to get keys from it.
Submitted by Nidhi, on June 10, 2022
Problem statement
In this program, we will create a collection of key/value pair information using the HashMap collection. Then we will get keys from HashMap using the keySet() method and print the keys.
Source Code
The source code to get keys from a HashMap collection is given below. The given program is compiled and executed successfully.
// Java program to get keys from a
// HashMap collection
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap < Integer, String > emp = new HashMap < > ();
emp.put(101, "Amit");
emp.put(102, "Arun");
emp.put(103, "Akas");
emp.put(104, "Ram");
emp.put(105, "Mohan");
Set < Integer > keys = emp.keySet();
System.out.println("Keys:");
for (Integer key: keys) {
System.out.println(key);
}
}
}
Output
Keys:
101
102
103
104
105
Explanation
In the above program, we imported the "java.util.*" package to use the HashMap class. Here, we created a public class Main.
The Main class contains a main() method. The main() method is the entry point for the program. And, created an object of the HashMap class and store the employee information using the put() method. Then we got the stored keys from the HashMap collection using the keySet() method and printed the keys.
Java HashMap Programs »