Java WeakHashMap

WeakHashMap is a class which is available in java.util package. The WeakHashMap is a class of the Java collections framework provides the functionality of hash table data structure. In Java WeakHashMap, elements are stored in key/value pairs. Keys are unique values associated with individual values. WeakHashMap cannot contains duplicate keys.

The object of a weak reference type can be garbage collected in Java if the reference is no longer used in the program.

WeakHashMap Syntax:
                        
                            WeakHashMap<K, V> numbers = new WeakHashMap<>();
                            WeakHashMap<String, Integer> numbers = new WeakHashMap<>();
                        
                    

By default,

  1. the capacity of the map will be 16
  2. the load factor will be 0.75

Basic Operations on Java WeakHashMap
  1. 1. Insert Elements to WeakHashMap
  2. 2. Access WeakHashMap Elements
  3. 3. Removed WeakHashMap Elements
Methods of WeakHashMap
Method Name Description
put() inserts the specified key/value mapping to the map.
putAll() inserts all the entries from the specified map to this map.
putIfAbsent() inserts the specified key/value mapping to the map if the specified key is not present in the map.
entrySet() returns a set of all the key/value mapping of the map.
keySet() returns a set of all the keys of the map.
values() returns a set of all the values of the map.
get() Returns the value associated with the specified key. If the key is not found, it returns null.
getOrDefault() Returns the value associated with the specified key. If the key is not found, it returns the specified default value.
remove(key) returns and removes the entry associated with the specified key from the map.
remove(key, value) removes the entry from the map only if the specified key mapped to be the specified value and return a boolean value.
clear() removes all the entries from the map.
containsKey() checks if the map contains the specified key and returns a boolean value.
containsValue() checks if the map contains the specified value and returns a boolean value.
size() returns the size of the map.
isEmpty() checks if the map is empty and returns a boolean value.
1. Insert Elements to WeakHashMap
                        
                            import java.util.WeakHashMap;

                            class Main {
                                public static void main(String[] args) {
                                    // Creating WeakHashMap of even numbers
                                    WeakHashMap<String, Integer> evenNumbers = new WeakHashMap<>();

                                    String two = new String("Two");
                                    Integer twoValue = 2;

                                    // Using put()
                                    evenNumbers.put(two, twoValue);

                                    String four = new String("Four");
                                    Integer fourValue = 4;

                                    // Using putIfAbsent()
                                    evenNumbers.putIfAbsent(four, fourValue);
                                    System.out.println("WeakHashMap of even numbers: " + evenNumbers);

                                    //Creating WeakHashMap of numbers
                                    WeakHashMap<String, Integer> numbers = new WeakHashMap<>();

                                    String one = new String("One");
                                    Integer oneValue = 1;
                                    numbers.put(one, oneValue);

                                    // Using putAll()
                                    numbers.putAll(evenNumbers);
                                    System.out.println("WeakHashMap of numbers: " + numbers);
                                }
                            }
                        
                    
2. Access WeakHashMap Elements
                        
                            import java.util.WeakHashMap;

                            class Main {
                                public static void main(String[] args) {
                                    // Creating WeakHashMap of even numbers
                                    WeakHashMap<String, Integer> numbers = new WeakHashMap<>();

                                    String one = new String("One");
                                    Integer oneValue = 1;
                                    numbers.put(one, oneValue);

                                    String two = new String("Two");
                                    Integer twoValue = 2;
                                    numbers.put(two, twoValue);

                                    System.out.println("WeakHashMap: " + numbers);

                                    // Using entrySet()
                                    System.out.println("Key/Value mappings: " + numbers.entrySet());

                                    // Using keySet()
                                    System.out.println("Keys: " + numbers.keySet());

                                    // Using values()
                                    System.out.println("Values: " + numbers.values());

                                    // Using get()
                                    int value1 = numbers.get("Two");
                                    System.out.println("Using get(): " + value1);

                                    // Using getOrDefault()
                                    int value2 = numbers.getOrDefault("Four", 4);
                                    System.out.println("Using getOrDefault(): " + value2);
                                }
                            }
                        
                    
3. Removed WeakHashMap Elements
                        
                            import java.util.WeakHashMap;

                            class Main {
                                public static void main(String[] args) {
                                    // Creating WeakHashMap of even numbers
                                    WeakHashMap<String, Integer> numbers = new WeakHashMap<>();

                                    String one = new String("One");
                                    Integer oneValue = 1;
                                    numbers.put(one, oneValue);

                                    String two = new String("Two");
                                    Integer twoValue = 2;
                                    numbers.put(two, twoValue);

                                    System.out.println("WeakHashMap: " + numbers);

                                    // Using remove() with single parameter
                                    int value = numbers.remove("Two");
                                    System.out.println("Removed value: " + value);

                                    // Using remove() with 2 parameters
                                    boolean result = numbers.remove("One", 3);
                                    System.out.println("Is the entry {One=3} removed? " + result);

                                    System.out.println("Updated WeakHashMap: " + numbers);
                                }
                            }
                        
                    
HashMap vs WeakHashMap

  1. - When the key of a weak hashmap is set to null and perform garbage collection, the key is removed.
  2. - keys of weak hashmaps are of weak reference type. This means the entry of a map are removed by the garbage collector if the key to that entry is no longer used.
  3. - This is useful to save resources.
  4. - When the key of the hashmap is set to null and perform garbage collection, the key is not removed.
  5. - keys of hashmaps are of strong reference type. This means the entry of a map is not removed by the garbage collector even though the key to that entry is no longer used.