Java WeakHashMap Methods Example

WeakHashMap is a specialized implementation of the Map interface from the java.util package where keys are stored as weak references. If a key is not referred to outside of the WeakHashMap, it can be garbage collected, and its entry is removed from the map.

Java WeakHashMap Common Methods

import java.util.WeakHashMap;

public class WeakHashMapExample {

    public static void main(String[] args) {
        // 1. Create a `WeakHashMap`
        WeakHashMap<String, String> weakMap = new WeakHashMap<>();

        // 2. Add entries to the `WeakHashMap`
        weakMap.put("One", "First");
        weakMap.put("Two", "Second");
        weakMap.put("Three", "Third");
        System.out.println("2. WeakHashMap content: " + weakMap);

        // 3. Check if a key is present
        boolean hasKeyTwo = weakMap.containsKey("Two");
        System.out.println("3. Contains key 'Two'? " + hasKeyTwo);

        // 4. Get a value using its key
        String valueOfThree = weakMap.get("Three");
        System.out.println("4. Value for key 'Three': " + valueOfThree);

        // 5. Remove an entry using its key
        System.out.println("5. WeakHashMap after removing key 'Two': " + weakMap);

        // 6. Check the size of the WeakHashMap
        int size = weakMap.size();
        System.out.println("6. Size of the WeakHashMap: " + size);


2. WeakHashMap content: {One=First, Two=Second, Three=Third}
3. Contains key 'Two'? true
4. Value for key 'Three': Third
5. WeakHashMap after removing key 'Two': {One=First, Three=Third}
6. Size of the WeakHashMap: 2


1. Initialized a WeakHashMap named weakMap.

2. Added key-value pairs using the put() method.

3. Checked the presence of a specific key with the containsKey() method.

4. Retrieved the value associated with a particular key using the get() method.

5. Removed a key-value pair using the remove() method.

6. Checked the number of key-value pairs using the size() method.

WeakHashMap is similar to HashMap with a key difference: in WeakHashMap, the keys are held weakly, which means if a WeakHashMap key is not referenced outside, it becomes eligible for garbage collection.