Get list of keys from hashmap java

We can use keySet() method to get list of keys from hashmap java.

keySet(): Returns a Set that contains the keys in this map. This method provides a set-view of the keys in this map.

Syntax:

public Set keySet()

Example

package com.w3spoint;
 
import java.util.HashMap;
import java.util.Set;
 
public class Test {
  public static void main(String args[]){
	//Create HashMap object.
	HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
 
	//Add objects to the HashSet.
	hashMap.put(4, "Roxy");
	hashMap.put(2, "Sunil");
	hashMap.put(5, "Sandy");
	hashMap.put(1, "Munish");
	hashMap.put(3, "Pardeep");
 
	//Print the HashMap object.
	System.out.println("HashMap elements:");
	System.out.println(hashMap);
 
	//Get all keys
	Set<Integer> keys = hashMap.keySet();
        for(Integer key: keys){
            System.out.println(key);
        }
  }
}

Output

HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
1
2
3
4
5
Please follow and like us:
Content Protection by DMCA.com