WeakHashMap is a part of the java.util package that implements the Map interface. It stores key–value pairs like a HashMap but allows keys to be garbage-collected when they are no longer in ordinary use. This means that entries can disappear automatically when the key is no longer referenced elsewhere.
- Internally uses a hash table-based implementation with weak keys.
- Keys eligible for garbage collection are removed automatically.
- Both null keys and null values are supported.
Declaration of WeakHashmap
WeakHashMap<K, V> map = new WeakHashMap<>();
- K -> Type of keys in the map
- V –> Type of values in the map
import java.util.Map;
import java.util.WeakHashMap;
public class WeakHashMapExample {
public static void main(String[] args) {
WeakHashMap<String, String> map = new WeakHashMap<>();
// Add entries
map.put("Java", "Language1");
map.put("Python", "Language2");
map.put("C++", "Language3");
System.out.println("WeakHashMap elements: " + map);
// Access an element
System.out.println("Value for 'Python': " + map.get("Python"));
// Remove an element
map.remove("C++");
System.out.println("After removing 'C++': " + map);
// Iterate elements correctly using Map.Entry
System.out.println("Iterating WeakHashMap:");
for (Map.Entry<String, String> e : map.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
}
}
Output
WeakHashMap elements: {Java=Language1, C++=Language3, Python=Language2}
Value for 'Python': Language2
After removing 'C++': {Java=Language1, Python=Language2}
Iterating WeakHashMap:
Java -> Language1
...Hierarchy of WeakHashMap
WeakHashMap extends AbstractMap<K, V> and implements Map<K, V>, Cloneable, Serializable in the java.util package.

Constructors Of WeakHashMap
1. WeakHashMap():
Creates an empty WeakHashMap with default initial capacity 16 and load factor 0.75.
WeakHashMap<K, V> map = new WeakHashMap<>();
2. WeakHashMap(int initialCapacity):
Creates an empty WeakHashMap with the specified initial capacity and default load factor.
WeakHashMap<K, V> map = new WeakHashMap<>(50, 0.5f);
3. WeakHashMap(int initialCapacity, float loadFactor):
Creates an empty WeakHashMap with the specified capacity and load factor.
 WeakHashMap<K, V> map = new WeakHashMap<>(50, 0.5f);
4. WeakHashMap(Map m):
Creates a new WeakHashMap with the same mappings as the specified map.
Map<K, V> m = new HashMap<>();
WeakHashMap<K, V> map = new WeakHashMap<>(m);
import java.util.WeakHashMap;
public class WeakHashMapExample1 {
public static void main(String[] args) {
// Creating a WeakHashMap
WeakHashMap<String, String> map = new WeakHashMap<>();
// Adding elements using put()
map.put("Java", "Language1");
map.put("Python", "Language2");
map.put("C++", "Language3");
// Displaying the WeakHashMap
System.out.println("WeakHashMap elements: " + map);
// Removing an element
map.remove("C++");
System.out.println("After removing 'C++': " + map);
}
}
Output
WeakHashMap elements: {Java=Language1, C++=Language3, Python=Language2}
After removing 'C++': {Java=Language1, Python=Language2}
Methods in WeakHashMap
| Method | Action Performed |
|---|---|
| clear() | Removes all of the mappings from this map. The map will be empty after this call returns. |
| containsValue(Object value) | Returns true if this map maps one or more keys to the specified value. |
| containsKey(Object key) | Returns true if this map contains a mapping for the specified key. |
| entrySet() | Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. |
| get(Object key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
| isEmpty() | Returns true if this map contains no key-value mappings. This result is a snapshot, and may not reflect unprocessed entries that will be removed before next attempted access because they are no longer referenced. |
| keySet() | Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. |
| put(K key, V value) | Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced. |
| putAll(Map m) | Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map. |
| remove(Object key) | Removes the mapping for a key from this weak hash map if it is present. More formally, if this map contains a mapping from key k to value v such that (key==null ? k==null: key.equals(k)), that mapping is removed. |
| size() | Returns the number of key-value mappings in this map. This result is a snapshot, and may not reflect unprocessed entries that will be removed before the next attempted access because they are no longer referenced. |
| values() | Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations. |