Java TreeMap keySet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

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");
CallWhat 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

ParameterDescription
(none)keySet takes no parameters.

Return Value

Return ValueDescription
Set<K>A live view of the keys; its iterator returns them in ascending order.

Compare with Similar Methods

Other views of a TreeMap:

MethodHow it differs
values()The values, ordered by their keys.
entrySet()Keys and values together.
navigableKeySet()Same keys with navigation methods.
HashMap.keySet()Same idea, but in no particular order.

Java Examples

Example 1 — Print a Phone Directory Alphabetically

Names are added in any order; looping over keySet() lists them alphabetically.

Java
import java.util.Set;
import java.util.TreeMap;

public class TreeMapKeySetDirectory {
    public static void main(String[] args) {
        TreeMap<String, String> phone = new TreeMap<>();
        phone.put("Linus", "555-0142");
        phone.put("Ada", "555-0199");
        phone.put("Tim", "555-0107");
        phone.put("Grace", "555-0163");

        Set<String> names = phone.keySet();
        System.out.println("names: " + names);
        for (String name : names) {
            System.out.println(name + ": " + phone.get(name));
        }
    }
}

How It Works

  1. Alphabetical for free. The set prints Ada, Grace, Linus, Tim, the sorted order of the keys, not the order of the put calls.
  2. Key loop plus lookup. Each name is used with get to print its number; this works, though entrySet() avoids the extra O(log n) search per key.
  3. A view, not a snapshot. names was obtained once, yet any later put would show up in it.

Example 2 — Remove Test Accounts by Name

keySet().removeIf deletes every mapping whose key matches a condition (Java 8).

Java
import java.util.TreeMap;

public class TreeMapKeySetRemoveIf {
    public static void main(String[] args) {
        TreeMap<String, Integer> users = new TreeMap<>();
        users.put("alice", 31);
        users.put("test1", 0);
        users.put("bob", 27);
        users.put("test2", 0);

        boolean removed = users.keySet().removeIf(name -> name.startsWith("test"));
        System.out.println("removed any: " + removed);
        System.out.println("users: " + users);
        System.out.println("removed again: " + users.keySet().removeIf(name -> name.startsWith("test")));
    }
}

How It Works

  1. A predicate on keys. The lambda tests each user name, and both "test1" and "test2" match startsWith("test").
  2. Whole mappings go. Removing the key from the view removes its value too, leaving only alice and bob.
  3. 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);
    }
}

How It Works

  1. 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.
  2. Half-finished work. Because the loop stopped early, order 4 is still there; the exception does not undo the removal of order 2.
  3. 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.

Next: lastEntry()

Read the pair with the largest key, or null when empty.

lastEntry() 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.

13 people found this page helpful