There are a few ways to remove all entries from a Java Map. The right choice depends on whether other parts of your code hold a reference to the same map object, and whether thread safety matters.
Method 1: clear() — Empties the Existing Map Object
clear() removes all key-value pairs from the map in-place. The map object itself remains — it's the same reference, now empty. All implementations of the Map interface support it: HashMap, TreeMap, LinkedHashMap, ConcurrentHashMap, and others.
import java.util.HashMap;
import java.util.Map;
public class ClearMapExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
System.out.println("Before: " + map);
System.out.println("Size: " + map.size());
map.clear();
System.out.println("After: " + map);
System.out.println("Size: " + map.size());
}
}
Output:
Before: {1=one, 2=two, 3=three, 4=four, 5=five}
Size: 5
After: {}
Size: 0
After clear(), isEmpty() returns true and size() returns 0. The map is ready to be repopulated.
Method 2: Reassignment — Replace With a New Map
If the variable is local or only you hold a reference to it, replacing it with a new map is equally valid:
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
// Replace with a fresh empty map
map = new HashMap<>();
System.out.println(map); // {}
Important caveat: If another variable also points to the original map, that variable still sees the old entries. The reassignment only changes this reference, not the underlying object.
Map<Integer, String> original = new HashMap<>();
original.put(1, "one");
Map<Integer, String> alias = original; // both point to same object
original = new HashMap<>(); // only original changes reference
System.out.println(alias); // {1=one} — alias still sees old data
System.out.println(original); // {} — new empty map
When in doubt, use clear() — it affects the shared object rather than just the local pointer.
clear() Across Map Implementations
The behavior of clear() is consistent across all standard Map implementations:
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
Map<String, Integer> hashMap = new HashMap<>();
Map<String, Integer> treeMap = new TreeMap<>();
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
hashMap.put("a", 1);
treeMap.put("b", 2);
linkedHashMap.put("c", 3);
concurrentMap.put("d", 4);
hashMap.clear();
treeMap.clear();
linkedHashMap.clear();
concurrentMap.clear();
System.out.println(hashMap.isEmpty()); // true
System.out.println(treeMap.isEmpty()); // true
System.out.println(linkedHashMap.isEmpty()); // true
System.out.println(concurrentMap.isEmpty()); // true
Thread Safety
If your map is accessed from multiple threads, the approach matters:
| Map Type | clear() Thread-Safe? | Notes |
|---|---|---|
HashMap | No | Requires external synchronization |
Collections.synchronizedMap() | Yes | Synchronized on the map object |
ConcurrentHashMap | Yes | Internally handles concurrent access |
TreeMap | No | Requires external synchronization |
For a ConcurrentHashMap, clear() is safe to call from multiple threads. For a regular HashMap, always synchronize externally if other threads might access the map during the clear:
synchronized (map) {
map.clear();
}
Checking if a Map is Already Empty
Use isEmpty() to check before operating on a map you expect to be empty — or to guard against redundant work:
if (!map.isEmpty()) {
map.clear();
}
// Or simply — clear() on an empty map is a no-op, safe to call unconditionally
map.clear();
Calling clear() on an already-empty map is safe and does nothing. There's no need to check first.
clear() vs. Iterating and Removing
Before Java had clear(), you might have removed entries one by one with an iterator. This is verbose and much slower:
// Old way — DO NOT do this
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
// Modern way — one method call
map.clear();
clear() is O(n) just like iterating, but its internal implementation is optimized and avoids iterator overhead.
Summary
Use clear() when you want to empty the existing map object in place — especially when other code holds a reference to the same map. Use reassignment (map = new HashMap<>()) only when you're certain no other variable shares a reference to the old map. For concurrent access, ConcurrentHashMap.clear() is safe without additional synchronization.
No comments :
Post a Comment
Please leave your message queries or suggetions.
Note: Only a member of this blog may post a comment.