Java TreeMap clear() Method

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

Definition

In Java, clear() removes all mappings from a TreeMap. Afterwards size() is 0 and isEmpty() is true, but the map object, its comparator, and any views you obtained earlier remain usable.

Called on a range view such as headMap() or subMap(), clear() removes only the keys in that range from the backing map, which makes it the quickest way to delete a slice of keys.

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

Clear the whole map or just one range of it.

Java
TreeMap<Integer, String> orders = new TreeMap<>();
orders.clear();                     // everything
orders.headMap(100).clear();        // only keys below 100
CallWhat it does
map.clear()Removes every mapping.
map.subMap(a, b).clear()Removes the keys in [a, b).
map.keySet().clear()Same as map.clear(), through a view.

Clearing and refilling the same map is fine; you do not need a new TreeMap<>(). Reusing the object also keeps a custom comparator, which a fresh map would need to be given again.

Library declarations
Java
// java.util.TreeMap<K, V>
public void clear()

// Declared in Map<K, V>

Parameters

ParameterDescription
(none)clear takes no parameters.

Return Value

Return ValueDescription
voidNothing; the map is empty afterwards.

Compare with Similar Methods

Ways to remove many mappings:

MethodHow it differs
remove(k)One key at a time.
headMap(k).clear()Everything below k.
values().removeIf(p)Every mapping whose value matches.
HashMap.clear()Same method on a hash map.

Java Examples

Example 1 — Reset the Order Board at Closing Time

The same map is emptied in the evening and reused the next morning.

Java
import java.util.TreeMap;

public class TreeMapClearReset {
    public static void main(String[] args) {
        TreeMap<Integer, String> orders = new TreeMap<>();
        orders.put(1, "latte");
        orders.put(2, "tea");
        orders.put(3, "mocha");

        System.out.println("orders today: " + orders.size());
        orders.clear();
        System.out.println("after clear: " + orders + ", empty: " + orders.isEmpty());

        orders.put(1, "espresso");
        System.out.println("next morning: " + orders);
    }
}

How It Works

  1. Three orders before closing. size() reports 3 just before the board is wiped.
  2. Empty but alive. After clear() the map prints as {} and isEmpty() is true; the variable still refers to the same usable object.
  3. Order numbers restart. Key 1 is free again, so the first order of the new day can reuse it.

Example 2 — Delete a Range of Exam Marks

Clearing a subMap or tailMap view removes only the keys inside it.

Java
import java.util.TreeMap;

public class TreeMapClearRange {
    public static void main(String[] args) {
        TreeMap<Integer, String> marks = new TreeMap<>();
        marks.put(35, "Ola");
        marks.put(48, "Ben");
        marks.put(62, "Sia");
        marks.put(77, "Tom");
        marks.put(91, "Uma");

        marks.subMap(40, 70).clear();
        System.out.println("after subMap(40, 70).clear(): " + marks);
        marks.tailMap(90).clear();
        System.out.println("after tailMap(90).clear(): " + marks);
    }
}

How It Works

  1. A middle slice disappears. 48 and 62 lie in [40, 70), so clearing that view deletes Ben and Sia from marks.
  2. The rest is untouched. 35, 77, and 91 are outside the range and survive the first clear.
  3. Trim the top. tailMap(90) covers 90 and above, and clearing it removes Uma's 91, leaving two marks.

Example 3 — Key and Value Views Stay Connected

Clearing through keySet() empties the map, and both views show the next put.

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

public class TreeMapClearViews {
    public static void main(String[] args) {
        TreeMap<String, Integer> votes = new TreeMap<>();
        votes.put("red", 4);
        votes.put("blue", 7);
        votes.put("green", 2);

        Set<String> keys = votes.keySet();
        Collection<Integer> counts = votes.values();
        keys.clear();
        System.out.println("map after keySet().clear(): " + votes);

        votes.put("teal", 1);
        System.out.println("keys: " + keys + ", counts: " + counts);
    }
}

How It Works

  1. Clearing a view clears the map. keys.clear() removes every mapping, so votes prints as empty.
  2. The views are not broken. keys and counts still refer to the live map rather than to the old contents.
  3. New data shows up everywhere. After put("teal", 1), the key view lists teal and the value view lists 1.

Frequently Asked Questions

It removes every mapping from the map, leaving it empty but still usable with the same comparator.
Clear a range view, such as map.headMap(k).clear() or map.subMap(a, b).clear(), or use keySet().removeIf(...).
Either works. clear() keeps the same object and comparator, which matters if other code holds a reference to the map or its views.
Yes. keySet(), values(), and entrySet() views stay connected and show any mappings added later.
On an unmodifiable wrapper it throws UnsupportedOperationException, and a loop iterating the map at the same time gets ConcurrentModificationException.

Next: clone()

Make a shallow copy that keeps the same sort order.

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

9 people found this page helpful