Java TreeSet contains() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

In Java, contains(o) returns true if the TreeSet holds an element matching o, and false otherwise.

Rather than scanning element by element, contains() walks the red-black tree in O(log n) time. Matching uses compareTo() or the set's Comparator returning 0, not equals().

An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe.

Syntax

Pass the candidate element; get back a boolean.

Java
TreeSet<String> allowed = new TreeSet<>(Arrays.asList("alice", "bob"));
boolean hasBob = allowed.contains("bob");   // true
boolean hasEve = allowed.contains("eve");   // false
CallWhat it does
set.contains(o)Checks membership in O(log n) time.
set.floor(o)Finds the closest match at or below o.
set.subSet(a, b).contains(o)True only if o is present and within bounds.
!set.contains(o)Checks that an element is missing.

For a TreeSet backed by a custom comparator that ignores case or extra fields, contains() returns true whenever compare == 0, even if equals() is false.

Library declarations
Java
// java.util.TreeSet<E>
public boolean contains(Object o)

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
o (Object)The element to look for. Must be comparable with the set's elements.

Return Value

Return ValueDescription
trueAn element comparing equal (result 0) exists in the set.
falseNo matching element was found.

Compare with Similar Methods

Searching and testing membership in a TreeSet:

MethodHow it differs
floor(e)Returns the matching element or the closest one below it.
ceiling(e)Returns the matching element or the closest one above it.
isEmpty()Checks whether the set has zero elements at all.
ArrayList.contains(o)Scans linearly in O(n) time using equals().

Java Examples

Example 1 — Check Approved Usernames in Sorted Order

Look up whether usernames appear in a sorted allowlist and verify missing names return false.

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetContainsUsers {
    public static void main(String[] args) {
        TreeSet<String> admins = new TreeSet<>(Arrays.asList("maya", "liam", "noah"));

        System.out.println("contains liam: " + admins.contains("liam"));
        System.out.println("contains zoe:  " + admins.contains("zoe"));
        System.out.println("range [a..n) has noah? " + admins.headSet("n").contains("noah"));
    }
}

How It Works

  1. Logarithmic search. Checking "liam" navigates down the balanced tree in O(log n) steps and returns true.
  2. Absent key. Searching for "zoe" reaches a leaf without a match and returns false.
  3. View bounds apply. "noah" exists in admins, yet headSet("n").contains("noah") returns false because "noah" >= "n".

Example 2 — How Comparator Equality Governs contains()

Use String.CASE_INSENSITIVE_ORDER so uppercase lookups find lowercase entries, and compare against equals().

Java
import java.util.TreeSet;

public class TreeSetContainsComparator {
    public static void main(String[] args) {
        TreeSet<String> commands = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        commands.add("start");
        commands.add("status");
        commands.add("stop");

        System.out.println("contains START: " + commands.contains("START"));
        System.out.println("contains Stop:  " + commands.contains("Stop"));
        System.out.println("equals check:   " + commands.first().equals("START"));
    }
}

How It Works

  1. Case ignored during lookup. commands.contains("START") calls the set's case-insensitive comparator, matching "start".
  2. Mixed case also matches. "Stop" compares as 0 against "stop", so contains() returns true.
  3. Comparator vs equals(). Even though "start".equals("START") is false, the tree search relies exclusively on the comparator.

Example 3 — NullPointerException and ClassCastException on Bad Lookups

See why searching a natural-order TreeSet<Integer> for null or a String throws an exception.

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetContainsErrors {
    public static void main(String[] args) {
        TreeSet<Integer> ports = new TreeSet<>(Arrays.asList(80, 443, 8080));

        try {
            ports.contains(null);
        } catch (NullPointerException e) {
            System.out.println("contains(null): " + e.getClass().getSimpleName());
        }

        try {
            ports.contains("443");
        } catch (ClassCastException e) {
            System.out.println("contains(String): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Null rejected immediately. Natural-order TreeSet explicitly forbids null lookups and throws NullPointerException.
  2. Type mismatch caught at runtime. Because contains(Object) accepts any object, passing "443" compiles and fails when compared with Integer.
  3. Fix the argument type. Always search a TreeSet<Integer> with an Integer (or int) rather than a String.

Frequently Asked Questions

It runs in O(log n) time by searching the balanced red-black tree rather than scanning every element.
It uses compareTo() or the custom Comparator returning 0, not equals().
Under natural ordering, contains(null) throws NullPointerException. Only a null-friendly Comparator allows null lookups.
Because the signature is contains(Object o) for Collection compatibility. At runtime, comparing a String with stored Integers throws ClassCastException.
It returns false rather than throwing an exception, even when the element exists in the backing TreeSet.

Next: descendingIterator()

Walk the elements one by one from largest to smallest.

descendingIterator() 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