Java TreeMap containsKey() Method

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

Definition

In Java, containsKey(key) returns true if the TreeMap has a mapping for key, and false otherwise. It also returns true for a key mapped to null, which get alone cannot tell you.

The check uses the same tree search as get, so it costs O(log n). "Present" means some stored key makes compare (or compareTo) return 0; equals is never called.

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

Pass a key; you get a boolean.

Java
TreeMap<String, String> accounts = new TreeMap<>();
accounts.put("coder42", "Ana");
boolean taken = accounts.containsKey("coder42");   // true
CallWhat it does
map.containsKey(k)true if k is a key.
map.headMap(x).containsKey(k)true only if k is a key and below x.
!map.containsKey(k)Typical guard before inserting.

If you need the value anyway, one get (plus a null check) is cheaper than containsKey followed by get.

Library declarations
Java
// java.util.TreeMap<K, V>
public boolean containsKey(Object key)

// Declared in Map<K, V>

Parameters

ParameterDescription
key (Object)The key to look for. Not null under natural ordering.

Return Value

Return ValueDescription
trueA key comparing equal to key is in the map (or in the view's range).
falseNo such key.

Compare with Similar Methods

Presence checks:

MethodHow it differs
containsValue(v)Searches values: a full O(n) scan.
get(k)Returns the value; null is ambiguous.
ceilingKey(k)Finds the nearest key at or above k when there is no exact one.
HashMap.containsKeyUses hashCode/equals instead of a comparator.

Java Examples

Example 1 — Register Usernames Only If Free

Two sign-up attempts: one name is free, one is already taken.

Java
import java.util.TreeMap;

public class TreeMapContainsKeyUsernames {
    public static void main(String[] args) {
        TreeMap<String, String> accounts = new TreeMap<>();
        accounts.put("coder42", "Ana");
        accounts.put("nightowl", "Ben");

        String[] wanted = {"sunrise", "coder42"};
        for (String name : wanted) {
            if (accounts.containsKey(name)) {
                System.out.println(name + " is taken by " + accounts.get(name));
            } else {
                accounts.put(name, "You");
                System.out.println(name + " registered");
            }
        }
        System.out.println(accounts.keySet());
    }
}

How It Works

  1. A free name. "sunrise" is not a key, so containsKey returns false and the account is created.
  2. A taken name. "coder42" is found, so the program reports its owner instead of overwriting Ana's account.
  3. Names stay sorted. keySet() lists coder42, nightowl, sunrise in alphabetical order, ready for a member list.

Example 2 — A Range View Only Contains Its Own Keys

headMap(1003) covers invoices below 1003. Ask the map and the view about the same numbers.

Java
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapContainsKeyRange {
    public static void main(String[] args) {
        TreeMap<Integer, String> invoices = new TreeMap<>();
        invoices.put(1001, "paid");
        invoices.put(1002, "open");
        invoices.put(1003, "open");

        SortedMap<Integer, String> firstTwo = invoices.headMap(1003);
        System.out.println("map has 1003: " + invoices.containsKey(1003));
        System.out.println("view has 1003: " + firstTwo.containsKey(1003));
        System.out.println("view has 1002: " + firstTwo.containsKey(1002));
    }
}

How It Works

  1. The full map knows 1003. Invoice 1003 is stored, so the map answers true.
  2. The view ends before 1003. headMap(1003) excludes its upper bound, so the view answers false for the same key.
  3. Keys in range are visible. 1002 lies below the bound and is in the map, so the view reports true.

Example 3 — Exact vs Case-Insensitive Key Checks

Store "Oslo" in two maps that compare keys differently, then try a null key.

Java
import java.util.TreeMap;

public class TreeMapContainsKeyComparator {
    public static void main(String[] args) {
        TreeMap<String, Integer> exact = new TreeMap<>();
        TreeMap<String, Integer> relaxed = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        exact.put("Oslo", 1);
        relaxed.put("Oslo", 1);

        System.out.println("exact has OSLO: " + exact.containsKey("OSLO"));
        System.out.println("relaxed has OSLO: " + relaxed.containsKey("OSLO"));
        try {
            exact.containsKey(null);
        } catch (NullPointerException e) {
            System.out.println("containsKey(null): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Natural order is case-sensitive. "OSLO".compareTo("Oslo") is not 0 (uppercase S sorts before lowercase s), so exact says false.
  2. The comparator says equal. relaxed compares ignoring case, finds "Oslo", and returns true.
  3. No null probes. Even a yes/no question needs a comparison, so containsKey(null) throws on a naturally ordered map.

Frequently Asked Questions

O(log n). It performs the same tree search as get.
Yes. That is the main reason to use it instead of checking get(key) != null.
No. It uses compareTo or the map's Comparator; a key is found when the comparison returns 0.
Yes. NullPointerException for a null key under natural ordering, and ClassCastException for a key that cannot be compared with the stored keys.
Call containsKey on a view such as headMap, tailMap, or subMap. It returns false for keys outside the view's range.

Next: containsValue()

Check whether any key maps to a value (a full scan).

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

15 people found this page helpful