Get Keys From HashMap in Java

Hassan Saeed Dec 10, 2020 Oct 05, 2020
  1. Use keySet() to Get a Set of Keys From a HashMap in Java
  2. Use keySet() to Get an Array of Keys From a HashMap in Java
Get Keys From HashMap in Java

This tutorial discusses methods to get the keys from a HashMap in Java.

Use keySet() to Get a Set of Keys From a HashMap in Java

The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap.

In the example below, we will first create a HashMap object, insert some values in it, and then use keySet() to get the keys.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        // Create a HashMap with some values
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("Monday", 5);
        map.put("Tuesday", 6);
        map.put("Wednesday", 10);
        
        // Invoke keySet() on the HashMap object to get the keys as a set
        Set<String> keys = map.keySet();
        for ( String key : keys ) {
            System.out.println( key );
        }
    }
}

Output:

Monday
Wednesday
Tuesday

Use keySet() to Get an Array of Keys From a HashMap in Java

Often we prefer to work with an array instead of a set. The below example illustrates how to use keySet() to get an array of keys from a HashMap in Java.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        // Create a HashMap with some values
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("Monday", 5);
        map.put("Tuesday", 6);
        map.put("Wednesday", 10);
        
        // Invoke keySet() and use toArray() to get an array of keys
        Object[] keys = map.keySet().toArray();
        for (int i=0; i<keys.length; i++) {
            System.out.println( keys[i] );
        }
    }
}

Output:

Monday
Wednesday
Tuesday

Related Article - Java HashMap