Home Java TreeMap Methods containsKey() Java TreeMap containsKey() Method 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.
TreeMap<String, String> accounts = new TreeMap<>();
accounts.put("coder42", "Ana");
boolean taken = accounts.containsKey("coder42"); // true Call What 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.util.TreeMap<K, V>
public boolean containsKey(Object key)
// Declared in Map<K, V> Parameters Parameter Description key (Object)The key to look for. Not null under natural ordering.
Return Value Return Value Description trueA key comparing equal to key is in the map (or in the view's range). falseNo such key.
Important
containsKey(null) throws NullPointerException with natural ordering, and a key of an incomparable type throws ClassCastException. Because matching uses compare, a case-insensitive map answers true for "OSLO" when "Oslo" is stored.
Compare with Similar Methods Presence checks:
Java Examples 1. Check a username 2. Inside a range view 3. Comparator decides Example 1 — Register Usernames Only If Free Two sign-up attempts: one name is free, one is already taken.
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());
}
} sunrise registered
coder42 is taken by Ana
[coder42, nightowl, sunrise] How It Works A free name. "sunrise" is not a key, so containsKey returns false and the account is created.A taken name. "coder42" is found, so the program reports its owner instead of overwriting Ana's account.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.
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));
}
} map has 1003: true
view has 1003: false
view has 1002: true How It Works The full map knows 1003. Invoice 1003 is stored, so the map answers true.The view ends before 1003. headMap(1003) excludes its upper bound, so the view answers false for the same key.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.
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());
}
}
} exact has OSLO: false
relaxed has OSLO: true
containsKey(null): NullPointerException How It Works Natural order is case-sensitive. "OSLO".compareTo("Oslo") is not 0 (uppercase S sorts before lowercase s), so exact says false.The comparator says equal. relaxed compares ignoring case, finds "Oslo", and returns true.No null probes. Even a yes/no question needs a comparison, so containsKey(null) throws on a naturally ordered map.Frequently Asked Questions How fast is TreeMap containsKey()? O(log n). It performs the same tree search as get.
Does containsKey() return true for a key mapped to null? Yes. That is the main reason to use it instead of checking get(key) != null.
Does TreeMap containsKey() use equals()? No. It uses compareTo or the map's Comparator; a key is found when the comparison returns 0.
Can containsKey() throw an exception? Yes. NullPointerException for a null key under natural ordering, and ClassCastException for a key that cannot be compared with the stored keys.
How do I check whether a key is inside a range? Call containsKey on a view such as headMap, tailMap, or subMap. It returns false for keys outside the view's range.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion