How to get all keys of HashMap

HashMap keyset() method is used to get all keys from hashmap java

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapGetAllKeys {

public static void main(String[] args) {

Map<Integer,String> hm = new HashMap<Integer,String>();

* Associates the specified value with the specified key in
this map (optional operation). If the map previously
contained a mapping for the key, the old value is
replaced by the specified value
hm.put(2, "amit");
hm.put(5, "yogesh");

* Returns a Set view of the keys contained in this map

Set<Integer> keys =hm.keySet();

for (Integer key : keys) {
System.out.println(" key ="+key);



key =1
key =2
key =3
key =4
key =5

A Guide to HashMap                                                                                                            Java Doc – HashMap

Leave a Reply

Your email address will not be published. Required fields are marked *

32 + = 34