Java HashMap keySet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, keySet() returns a Set<K> containing every key of a HashMap. The set is a view, not a copy: it always reflects the current keys, and removing a key from it removes the whole mapping from the map.

The view does not support adding, because a key without a value would make no sense. Like the map itself, it has no guaranteed order: keys come out in the order of the internal hash table.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety.

Syntax

No arguments; returns a Set<K> view.

Java
Map<String, Integer> stock = new HashMap<>();
stock.put("pears", 3);
Set<String> keys = stock.keySet();   // live view: [pears]
stock.put("plums", 7);               // keys now has 2 elements
CallWhat it does
for (K k : map.keySet())Loop over every key.
map.keySet().remove(k)Removes the mapping for k from the map.
map.keySet().retainAll(c)Keeps only mappings whose key is in c.
new ArrayList<>(map.keySet())An independent copy you can sort.

If you need the value too, loop over entrySet() instead of calling get(key) for every key; it saves one lookup per entry.

Library declarations
Java
// java.util.HashMap<K, V>
public Set<K> keySet()

// Declared in Map<K, V>

Parameters

ParameterDescription
NonekeySet() takes no parameters.

Return Value

Return ValueDescription
Set<K>A live view of the keys. Supports remove, removeAll, retainAll, removeIf, and clear, but not add or addAll.

Compare with Similar Methods

The three views and the loop helper:

MethodHow it differs
values()A view of the values (duplicates possible).
entrySet()A view of key/value pairs.
forEach(action)Runs code for each key and value without a view.
containsKey(k)Same as keySet().contains(k).

Java Examples

Example 1 — Loop Over the Keys of a Stock List

Print the key set, then use each key to read its quantity.

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

public class HashMapKeySetDemo {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("apples", 12);
        stock.put("pears", 0);
        stock.put("plums", 7);

        Set<String> items = stock.keySet();
        System.out.println("keys: " + items);
        for (String item : items) {
            System.out.println(item + " -> " + stock.get(item));
        }
    }
}

How It Works

  1. A Set of keys. keySet() hands back the three item names as a Set<String>; printing it uses square brackets like any set.
  2. Hash order. The keys appear in bucket order of the internal table, not in the order they were added; plums came out first here.
  3. Same order twice. The loop walks the same table, so it visits the keys in the same order the printed set showed.
  4. Lookup per key. stock.get(item) fetches each quantity; for loops that need both parts, entrySet() avoids this extra lookup.

Example 2 — The Key Set Is a Live View

Take the view first, then add to the map, remove through the view, and try to add to the view.

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

public class HashMapKeySetLive {
    public static void main(String[] args) {
        Map<String, String> owners = new HashMap<>();
        owners.put("car", "Ada");
        Set<String> keys = owners.keySet();

        owners.put("bike", "Ben");
        System.out.println("view sees new key: " + keys.contains("bike") + ", size " + keys.size());

        keys.remove("car");
        System.out.println("map after keys.remove: " + owners);

        try {
            keys.add("boat");
        } catch (UnsupportedOperationException e) {
            System.out.println("keys.add(\"boat\") -> UnsupportedOperationException");
        }
    }
}

How It Works

  1. View taken early. keys is created when the map holds only "car".
  2. Reflects later puts. After "bike" is added to the map, the same keys object contains it and reports size 2; nothing was copied.
  3. Writes through. keys.remove("car") deletes the car mapping, value and all, from owners.
  4. No adding. A key alone has no value to store, so add on the view throws UnsupportedOperationException.

Example 3 — Filter a Price List with retainAll and Sort the Keys

Keep only the items on a shopping list, then print them in alphabetical order.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashMapKeySetFilter {
    public static void main(String[] args) {
        Map<String, Integer> prices = new HashMap<>();
        prices.put("milk", 55);
        prices.put("bread", 40);
        prices.put("eggs", 72);
        prices.put("jam", 120);

        prices.keySet().retainAll(Arrays.asList("bread", "jam", "rice"));
        System.out.println("kept " + prices.size() + " items");

        List<String> names = new ArrayList<>(prices.keySet());
        Collections.sort(names);
        for (String name : names) {
            System.out.println(name + ": " + prices.get(name));
        }
    }
}

How It Works

  1. Bulk filter. retainAll on the key view removes every mapping whose key is not in the shopping list, so milk and eggs disappear from prices.
  2. Extra names are harmless. "rice" is on the list but not in the map; retainAll never adds anything.
  3. Copy to sort. A Set view cannot be sorted, so the keys are copied into an ArrayList and sorted alphabetically.
  4. Deterministic output. Printing from the sorted list gives bread before jam on every JDK, regardless of hash order.

Frequently Asked Questions

Call map.keySet(). It returns a Set view of every key that you can loop over.
No. It is a live view: it reflects later changes to the map, and removing from it removes mappings from the map.
A key needs a value. The view supports removal but throws UnsupportedOperationException for add() and addAll().
In the internal hash-table order, which is not guaranteed and can change as the map grows. Sort a copy, or use a TreeMap or LinkedHashMap when order matters.
Copy them: List<String> keys = new ArrayList<>(map.keySet()); then call Collections.sort(keys).

Next: merge()

Insert a value, or combine it with the existing one.

merge() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful