In this example we will show how to get a Set of keys contained in HashMap with keySet method of java HashMap class.
Source Code
package com.beginner.examples;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class GetHashMapKeyExample {
public static void main(String[] args) {
//Create a HashMap object
HashMap map = new HashMap();
//Put Key-value
map.put("1", "Jan");
map.put("2", "Feb");
map.put("3", "Mar");
map.put("4", "Apr");
map.put("5", "May");
//Gets a collection of all the keys in the HashMap
Set indexSet = map.keySet();
//Iterate through the collection using an iterator
Iterator iterator = indexSet.iterator();
while(iterator.hasNext())
{
String key = iterator.next();
String value = map.get(key);
System.out.println(key+"::"+value);
}
}
}
Output:
3::Mar
2::Feb
1::b
5::May
4::Apr
References
Imported packages in Java documentation: