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
Call
What 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
Parameter
Description
None
keySet() takes no parameters.
Return Value
Return Value
Description
Set<K>
A live view of the keys. Supports remove, removeAll, retainAll, removeIf, and clear, but not add or addAll.
HashMap iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
A Set of keys.keySet() hands back the three item names as a Set<String>; printing it uses square brackets like any set.
Hash order. The keys appear in bucket order of the internal table, not in the order they were added; plums came out first here.
Same order twice. The loop walks the same table, so it visits the keys in the same order the printed set showed.
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");
}
}
}
Output
view sees new key: true, size 2
map after keys.remove: {bike=Ben}
keys.add("boat") -> UnsupportedOperationException
How It Works
View taken early.keys is created when the map holds only "car".
Reflects later puts. After "bike" is added to the map, the same keys object contains it and reports size 2; nothing was copied.
Writes through.keys.remove("car") deletes the car mapping, value and all, from owners.
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));
}
}
}
Output
kept 2 items
bread: 40
jam: 120
How It Works
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.
Extra names are harmless. "rice" is on the list but not in the map; retainAll never adds anything.
Copy to sort. A Set view cannot be sorted, so the keys are copied into an ArrayList and sorted alphabetically.
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).