What is the WeakHashMap.getOrDefault method in Java?
WeakHashMapis a kind ofMapthat is implemented based on theHashTable. TheWeakHashMaponly stores the WeakReference type as keys. Once the key is no longer used, the respective mapping is automatically removed once the garbage collection is done.
The getOrDefault(key, defaultVaule) method of WeakHashMap will:
-
Return
Default Valueif there is no mapping for the passedkey. -
Return the value mapped to the key if there is a mapping present for the passed
key.
Syntax
public V getOrDefault(Object key,V defaultValue)
Parameters
key: The key whose value is to be returned.defaultValue: The default mapping ofkey.
Return value
-
The method returns
Default Valueif there is no mapping for the passedkey. -
The method returns the value mapped to
keyif there is a mapping present for the passedkey.
Code
The code below demonstrates how to use the getOrDefault() method.
import java.util.WeakHashMap;class DefaultVaue {public static void main(String[] args) {// create an WeakHashMapWeakHashMap<Integer, String> numbers = new WeakHashMap<>();// add items in hashmapnumbers.put(1, "One");numbers.put(2, "Two");numbers.put(3, "Three");// print the itemsSystem.out.println("The WeakHashMap is - " + numbers);System.out.print("\nGetting value for key 5 using get(5) Method :" );System.out.println(numbers.get(5));System.out.print("\nGetting value for key 5 using getOrDefault(5, 'Default Value') Method :" );System.out.println(numbers.getOrDefault(5, "Default value"));System.out.print("\nGetting value for key 1 using getOrDefault Method :" );System.out.println(numbers.getOrDefault(1, "Default value"));}}
Explanation
In the code above, we:
-
Create a
WeakHashMapwith the namenumbers. -
Add three entries to
numbers. -
Call the
getmethod for the key5. This returnsnullbecause there is no value mapping for the key5. -
Call the
getOrDefault(5, "Default Value")method. This returnsDefault Valuebecause there is no value mapping for the key5, so the default value return is passed. -
Call the
getOrDefault(1, "Default Value")method. This returnsOnebecause the valueOneis mapped for the key1.