Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java HashMap keySet: Iteration, Behavior, and Pitfalls

How HashMap.keySet() works: a live Set view of keys, safe iteration patterns, and performance and concurrency implications.

~6 min readJava
#java#hashmap#keyset#iteration
A Java HashMap with a keySet view showing keys extracted from the map, illustrating the relationship between the map and its key set.

HashMap.keySet() returns a Set view of the keys contained in the map. It is not a snapshot: the set is backed by the map, so changes to the map are reflected in the set, and removing keys from the set removes corresponding entries from the map. This behavior is the source of both its efficiency and several common mistakes.

What keySet() Actually Returns

keySet() returns a Set<K> that is dynamically tied to the map. The returned set does not copy the keys; it provides a window into the map's internal state. This means that if you add or remove entries from the map after obtaining the key set, the set reflects those changes immediately. Conversely, removing a key from the set removes the corresponding entry from the map.

java
Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); Set<String> keys = map.keySet(); System.out.println(keys.size()); // 2 map.put("c", 3); System.out.println(keys.size()); // 3 keys.remove("a"); System.out.println(map.containsKey("a")); // false

Note that you cannot add a key to the set. The add() method throws UnsupportedOperationException because adding a key without a value is meaningless for a map. This is a deliberate design decision to preserve the map's integrity.

Iterating Over the Key Set

The most common use of keySet() is to iterate over all keys. You can use a for-each loop, an explicit iterator, or a stream.

java
Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); // For-each for (String key : map.keySet()) { System.out.println(key); } // Iterator Iterator<String> it = map.keySet().iterator(); while (it.hasNext()) { String key = it.next(); System.out.println(key); } // Stream map.keySet().stream().forEach(System.out::println);

HashMap does not guarantee any iteration order. The order depends on the hash function, the initial capacity, and the load factor. If you need a predictable order, use LinkedHashMap or TreeMap instead.

Modifying the Map While Iterating

If you structurally modify the map while iterating over its key set (except through the iterator's own remove method), the iterator will throw ConcurrentModificationException. This is fail-fast behavior: the iterator detects that the map has been changed and fails quickly rather than risking undefined behavior.

java
Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); for (String key : map.keySet()) { if (key.equals("a")) { map.remove(key); // Throws ConcurrentModificationException } }

To remove entries safely during iteration, use the iterator's remove method:

java
Iterator<String> it = map.keySet().iterator(); while (it.hasNext()) { String key = it.next(); if (key.equals("a")) { it.remove(); // Safe } }

The iterator's remove updates the map and the iterator's internal state consistently, so no exception is thrown. When you need to filter entries while iterating with an explicit iterator, this is the direct safe approach; the removeIf method described later also works because it uses the iterator internally.

Performance and Memory Behavior

Obtaining the key set is an O(1) operation because it just returns an internal view object. Iterating over the key set is O(capacity + n) in the worst case, where n is the number of entries and capacity is the size of the internal hash table, because the iterator may scan empty buckets; for a reasonably sized map this is effectively O(n). The constant factor depends on the hash table's internal structure, including capacity and how many buckets are empty.

Because keySet() returns a view, it does not allocate a separate collection of keys. This makes it memory-efficient compared to copying all keys into a new ArrayList. However, holding a reference to the key set keeps the entire map alive, even if you no longer need the map itself. If you only need the keys for a short period, it is fine to use the view directly. If you need to store the keys for later use, consider copying them into a new set to allow the map to be garbage-collected.

Common Pitfalls and How to Avoid Them

A frequent mistake is using keySet() to check whether a key exists. This is inefficient because it iterates over all keys:

java
boolean contains = map.keySet().contains(key); // O(n)

Instead, use containsKey() which performs a direct hash lookup in O(1) average time:

java
boolean contains = map.containsKey(key); // O(1) average

Another pitfall is assuming that the key set is ordered. If your code relies on a specific iteration order, HashMap is the wrong choice. Use LinkedHashMap for insertion order or TreeMap for natural or custom ordering.

Also, be aware that the key set is not thread-safe. If multiple threads modify the map concurrently, you must synchronize access or use a concurrent map implementation like ConcurrentHashMap. Even with ConcurrentHashMap, the key set's iterator is weakly consistent and does not throw ConcurrentModificationException, but it may not reflect all concurrent changes.

When to Choose keySet() vs entrySet() vs values()

If you only need the keys, keySet() is the right choice. If you need both keys and values, entrySet() is more efficient because it gives you direct access to each Map.Entry without a separate lookup. Using keySet() and then calling map.get(key) for each key performs an extra hash lookup per entry, which is unnecessary overhead.

NeedRecommended methodWhy
Only keyskeySet()Returns the keys directly, no extra lookups
Keys and values togetherentrySet()Access both from the entry, avoids get() per key
Only valuesvalues()Returns a collection of values directly

For example, to sum all values, entrySet() avoids the extra lookup:

java
int sum = 0; for (Map.Entry<String, Integer> entry : map.entrySet()) { sum += entry.getValue(); }

Using keySet() would require map.get(key) inside the loop, which is redundant. The performance difference is small for small maps, but it becomes noticeable when iterating over large maps frequently.

Handling Null Keys and Other Edge Cases

HashMap allows one null key. The key set will include null if present. Iterating over a key set that contains null works fine, but be careful when using methods that don't accept null, such as Objects.requireNonNull or certain stream operations.

java
Map<String, Integer> map = new HashMap<>(); map.put(null, 1); for (String key : map.keySet()) { // key can be null }

If you use keySet().remove(null), it will remove the entry with the null key. This is consistent with map.remove(null).

Another edge case: if the map is empty, keySet() returns an empty set. That set is still backed by the map, so if you later add entries, the set will reflect them. This is useful when you want to observe map growth through a stored set reference.

Key Set and Concurrent Modification in Multi-Threaded Code

In a single-threaded context, the fail-fast behavior of the key set iterator is a safety net. In a multi-threaded context, you must synchronize externally. The Collections.synchronizedMap() wrapper returns a synchronized map, but its key set iterator still requires manual synchronization when iterating:

java
Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>()); Set<String> keys = syncMap.keySet(); synchronized (syncMap) { for (String key : keys) { // safe iteration } }

Without the synchronized block, another thread could modify the map during iteration, causing undefined behavior or ConcurrentModificationException. For higher concurrency, use ConcurrentHashMap, which provides weakly consistent iterators that do not throw ConcurrentModificationException and reflect the state at some point during iteration.

Practical Example: Removing Keys That Match a Condition

A common task is to remove all keys that satisfy a predicate. Using the iterator's remove is the safe approach:

java
Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); map.put("c", 3); map.keySet().removeIf(key -> key.startsWith("b"));

The removeIf method (available since Java 8) uses the iterator internally and handles the removal correctly. It is more concise than an explicit iterator loop. This method works on any Collection, including the key set view.

If you need to remove entries based on both key and value, entrySet().removeIf() is more appropriate because it gives you access to the entry.

When to Avoid keySet() Entirely

If you are only interested in values, use values(). If you need to perform lookups by key, you don't need the key set at all—just use the map directly. The key set is only useful when you want to iterate over keys or pass the keys to another API that expects a Set. For example, if you want to check if two maps have the same keys, you can compare map1.keySet().equals(map2.keySet()). This works because Set.equals compares the contents, not the map identity.

However, be cautious: the key set's equals method is inherited from AbstractSet and will compare all keys, which is O(n). If you only need to check for a few keys, use containsKey instead.

Summary of Behavior and Best Use

The keySet() method is a lightweight, dynamic view of a HashMap's keys. It is ideal for iterating over keys and for removing entries via the iterator. Its main limitations are the lack of ordering, the inability to add keys, and the requirement to avoid structural modifications during iteration unless done through the iterator. For performance-sensitive code, prefer entrySet() when you need values as well, and always use containsKey() for existence checks. Understanding these details helps you use keySet() correctly and avoid subtle bugs in your Java applications.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.