In Java, keySet() returns a Set view of the keys of a TreeMap. Iterating it yields the keys in ascending sorted order, which is the usual way to loop over a map's keys.
The set is a view, not a copy: it reflects later changes to the map, and removing a key from it removes that mapping. In TreeMap it is the same object type as navigableKeySet(), just declared as Set<K>.
An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.
Syntax
Loop over it, test it, or remove from it.
Java
TreeMap<String, String> phone = new TreeMap<>();
Set<String> names = phone.keySet();
for (String name : names) { /* alphabetical order */ }
boolean known = names.contains("Ada");
Call
What it does
map.keySet()
Live view of the keys, sorted ascending.
map.keySet().removeIf(p)
Removes every mapping whose key matches.
new ArrayList<>(map.keySet())
A separate, editable copy of the keys.
keySet().contains(k) is the same O(log n) check as containsKey(k); there is no need to build the set first just to test a key.
Library declarations
Java
// java.util.TreeMap<K, V>
public Set<K> keySet()
// Declared in Map<K, V> and SortedMap<K, V>
Parameters
Parameter
Description
(none)
keySet takes no parameters.
Return Value
Return Value
Description
Set<K>
A live view of the keys; its iterator returns them in ascending order.
A predicate on keys. The lambda tests each user name, and both "test1" and "test2" match startsWith("test").
Whole mappings go. Removing the key from the view removes its value too, leaving only alice and bob.
The boolean tells you what happened. A second identical call finds nothing to delete and returns false.
Example 3 — ConcurrentModificationException and Iterator.remove()
Removing through the map inside a for-each loop fails; removing through the iterator works.
Java
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.TreeMap;
public class TreeMapKeySetCme {
public static void main(String[] args) {
TreeMap<Integer, String> orders = new TreeMap<>();
orders.put(1, "paid");
orders.put(2, "cancelled");
orders.put(3, "paid");
orders.put(4, "cancelled");
try {
for (Integer id : orders.keySet()) {
if (orders.get(id).equals("cancelled")) {
orders.remove(id);
}
}
} catch (ConcurrentModificationException e) {
System.out.println("map.remove inside for-each: " + e.getClass().getSimpleName());
}
System.out.println("after the failed loop: " + orders);
Iterator<Integer> it = orders.keySet().iterator();
while (it.hasNext()) {
if (orders.get(it.next()).equals("cancelled")) {
it.remove();
}
}
System.out.println("after iterator.remove: " + orders);
}
}
Output
map.remove inside for-each: ConcurrentModificationException
after the failed loop: {1=paid, 3=paid, 4=cancelled}
after iterator.remove: {1=paid, 3=paid}
How It Works
The loop breaks after the first removal. Order 2 is removed through the map, and the iterator's next step detects the change and throws.
Half-finished work. Because the loop stopped early, order 4 is still there; the exception does not undo the removal of order 2.
Remove through the iterator.it.remove() deletes the current key and keeps the iterator in sync, so the second loop clears every cancelled order.
Frequently Asked Questions
In ascending order according to the map's comparator or natural ordering.
No. It is a live view; later changes to the map appear in it, and removals through it change the map.
No. It throws UnsupportedOperationException because a key alone has no value. Use put.
Use an Iterator and call it.remove(), or call keySet().removeIf(...). Calling map.remove inside a for-each loop throws ConcurrentModificationException.
new ArrayList<>(map.keySet()) or new TreeSet<>(map.keySet()) creates an independent collection.