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
Call
What 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>
map after keySet().clear(): {}
keys: [teal], counts: [1]
How It Works
Clearing a view clears the map.keys.clear() removes every mapping, so votes prints as empty.
The views are not broken.keys and counts still refer to the live map rather than to the old contents.
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.