WeakHashMap in Java

WeakhashMap

In the previous blog we learned about LinkedHashMap and its methods. If you want to learn more about it, visit LinkedHashMap in Java. In this blog, we will go through the WeakHashMap class.


WeakHashMap

Before understanding what WeakHashMap is, we must know what is HashMap. WeakHashMap is an implementation of the Map interface which stores weak references to its keys. Storing just weak references means that a key-value pair can be garbage-collected when its key is no longer referenced outside of the WeakHashMap. WeakHashMap provides a simple way to harness the power of weak references. It is useful for implementing "registry-like" data structures, where the utility of an entry vanishes or disappears when its key is no longer reachable by any thread. WeakHashMap works identically to the HashMap with one difference i.e. If the Java memory manager no longer has a strong reference to the object supplied as a key, the entry in the map will be wiped or destroyed.


WeakHashMap Constructors

  1. WeakHashMap() - WeakHashMap() constructor constructs the empty WeakHashMap with the default initial capacity and load factor.
  2. WeakHashMap(int initialCapacity) - WeakHashMap(int initialCapacity) constructs the empty WeakHashMap with the specified initial capacity and default load factor.
  3. WeakHashMap(int initialCapacity, float loadFactor) - WeakHashMap(int initialCapacity, float loadFactor) creates a new WeakHashMap with the given initial capacity and load factor.
  4. WeakHashMap(Map map) - WeakHashMap(Map map) generates a new WeakHashMap that contains the same mappings as the specified Map.

Methods of WeakHashMap

  1. put()
  2. put() method adds or inserts the specified key/value mapping to the map.

  3. putAll()
  4. putAll() method adds or inserts all the elements from the specified map to this map.

  5. putIfAbsent()
  6. The putIfAbsent() method only inserts the specified value with the specified key into the map if it is not already there.

    Example of WeakHashMap using the above three methods

    import java.util.WeakHashMap;
    public class WeakHashMapPutMethodsEx {
      public static void main(String[] args) {
        WeakHashMap<String, String> wHashMap = new WeakHashMap<>();
        wHashMap.put("US", "United States");
        wHashMap.put("UK", "United Kingdom");
        wHashMap.put("IND", "India");
        wHashMap.put("JP", "Japan");
        System.out.println("WeakHashMap: "+ wHashMap);
        wHashMap.putIfAbsent("HK", "Hong Kong");
        System.out.println("WeakHashMap after using putIfAbsent(): "+ wHashMap);
        WeakHashMap<String, String> wHashMap2 = new WeakHashMap<>();
        wHashMap2.put("NP", "Nepal");
        wHashMap2.put("PAK", "Pakistan");
        wHashMap2.put("TUR", "Turkey");
        wHashMap2.put("BT", "Butan");
        System.out.println("WeakHashMap2: "+ wHashMap2);
        wHashMap.putAll(wHashMap2);
        System.out.println("Updated WeakHashMap: "+ wHashMap);
      }
    }

    Output

    WeakHashMap: {UK=United Kingdom, IND=India, US=United States, JP=Japan}
    WeakHashMap after using putIfAbsent(): {UK=United Kingdom, IND=India, US=United States, HK=Hong Kong, JP=Japan}
    WeakHashMap2: {NP=Nepal, BT=Butan, PAK=Pakistan, TUR=Turkey}
    Updated WeakHashMap: {NP=Nepal, UK=United Kingdom, PAK=Pakistan, BT=Butan, IND=India, US=United States, HK=Hong Kong, TUR=Turkey, JP=Japan}
  7. entrySet()
  8. entrySet() method returns a set of all the key-value mapping of the map.

  9. keySet()
  10. keySet() returns a set view of the keys in this map.

  11. values()
  12. values() method returns the view of all the values present in the entries of the map.

    Example of WeakHashMap using the above three methods

    import java.util.WeakHashMap;
    public class WeakHashMapDisplayingKeyValuesEx {
      public static void main(String[] args) {
        WeakHashMap<String, String> wHashMap = new WeakHashMap<>();
        wHashMap.put("US", "United States");
        wHashMap.put("UK", "United Kingdom");
        wHashMap.put("IND", "India");
        wHashMap.put("JP", "Japan");
        System.out.println("WeakHashMap: "+ wHashMap);
        System.out.println("WeakHashMap after using entrySet(): "+ wHashMap.entrySet());
        System.out.println("WeakHashMap after using keySet(): "+ wHashMap.keySet());
        System.out.println("WeakHashMap after using values(): "+ wHashMap.values());
      }
    }

    Output

    WeakHashMap: {US=United States, UK=United Kingdom, IND=India, JP=Japan}
    WeakHashMap after using entrySet(): [US=United States, UK=United Kingdom, IND=India, JP=Japan]
    WeakHashMap after using keySet(): [US, UK, IND, JP]
    WeakHashMap after using values(): [United States, United Kingdom, India, Japan]
  13. get()
  14. get() method returns the value of the specified key in the map.

  15. get()
  16. get() method returns the value of the specified key in the map.

  17. getOrDefult()
  18. The getOrDefult() method returns the value associated with the specified key. If the key is not found, the default value is returned.

    Example for LinkedHashMap using the above two methods

    import java.util.WeakHashMap;
    public class WeakHashMapGetAndRemoveMethodsEx {
      public static void main(String[] args) {
        WeakHashMap<String, String> wHashMap = new WeakHashMap<>();
        wHashMap.put("US", "United States");
        wHashMap.put("UK", "United Kingdom");
        wHashMap.put("IND", "India");
        wHashMap.put("JP", "Japan");
        System.out.println("WeakHashMap: "+ wHashMap);
        System.out.println("WeakHashMap after using get(): "+ wHashMap.get("UK"));
        System.out.println("WeakHashMap after using getOrDefault(): "+ wHashMap.getOrDefault("MV", "Maldives"));
      }
    }

    Output

    WeakHashMap: {US=United States, UK=United Kingdom, IND=India, JP=Japan}
    WeakHashMap after using get(): United Kingdom
    WeakHashMap after using getOrDefault(): Maldives
  19. remove()
  20. remove() method removes or deletes the specified values with the associated specified keys from the map.

  21. clear()
  22. clear() method removes all the key-value pairs of the map.

  23. isEmpty()
  24. isEmpty() method checks whether the weakhashmap is empty or not.

  25. size()
  26. size() method returns the number of entries in the weakhashmap.

  27. containsKey()
  28. containsKey() method checks if the mapping for the specified key is present in the weakhashmap. If the key is not present then it returns false.

  29. containsValue()
  30. containsValue() method checks if the specified value is present in one or more mappings of the weakhashmap or not. If the value is not present then it returns false.

    Example of WeakHashMap using the above methods

    import java.util.WeakHashMap;
    public class WeakHashMapMethodsEx {
      public static void main(String[] args) {
        WeakHashMap<String, String> wHashMap = new WeakHashMap<>();
        wHashMap.put("US", "United States");
        wHashMap.put("UK", "United Kingdom");
        wHashMap.put("IND", "India");
        wHashMap.put("JP", "Japan");
        System.out.println("WeakHashMap: "+ wHashMap);
        System.out.println("WeakHashMap after using get(): "+ wHashMap.get("UK"));
        System.out.println("WeakHashMap after using getOrDefault(): "+ wHashMap.getOrDefault("MV", "Maldives"));
        System.out.println("Element removed from the WeakHashMap: "+ wHashMap.remove("UK"));
        System.out.println("Updated WeakHashMap: "+ wHashMap);
        System.out.println("Mentioned key is present: "+ wHashMap.containsKey("IND"));
        System.out.println("Mentioned value is present: "+ wHashMap.containsValue("India"));
        wHashMap.clear();
        System.out.println("WeakHashMap after using clear(): "+ wHashMap);
        System.out.println("Is the WeakHashMap Empty: "+ wHashMap.isEmpty());
      }
    }

    Output

    WeakHashMap: {UK=United Kingdom, IND=India, US=United States, JP=Japan}
    WeakHashMap after using get(): United Kingdom
    WeakHashMap after using getOrDefault(): Maldives
    Element removed from the WeakHashMap: United Kingdom
    Updated WeakHashMap: {IND=India, US=United States, JP=Japan}
    Mentioned key is present: true
    Mentioned value is present: true
    WeakHashMap after using clear(): {}
    Is the WeakHashMap Empty: true

Core Java Tutorial

Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.