How to Get Keys in Map

The sample code below demonstrate how to get keys in map, whether its a hashmap or any implementation of Map. The method in Map that will get keys is:


This method will return a Set of object T where T is the type of object you have define to be the Keys when you initiliaze the Map.
Below is the actual implementation on how to get all keys in map using keySet() method.

public class MapKeys {

    private static Map<String, Person> map;

    public static void main(String[] args) {
        map = new HashMap<>();
        map.put("Sed", new Person());
        map.put("Joe", new Person());
        map.put("Richard", new Person());

        Set<String> keys = map.keySet();
        for(String key: keys) {

Note that the order of keys that was retrieve may be different from the order when you put the objects in Map.

Share this tutorial!