WeakHashMap
is a kind of Map
that is implemented based on the HashTable
. The WeakHashMap
only 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.
compute()
methodThe compute()
method uses the mapping function provided as an argument to compute a new value for the specified key. If the specified key is not present, then no operation is performed and the method returns null
.
Let’s look at the syntax of the function.
public V compute(K key, BiFunction remappingFunction)
key
: The key for which the new value is to be computed.
remappingFunction
:
BiFunction
that takes two arguments as input and returns a single value.BiFunction
will be updated as the value of the passed key of the map.null
from BiFunction
, then the mapping for the key will be removed.The compute()
method returns the new value associated with the key.
The code below demonstrates how to use the compute()
method.
import java.util.WeakHashMap; class Compute { public static void main( String args[] ) { WeakHashMap<String, Integer> map = new WeakHashMap<>(); map.put("Maths", 50); map.put("Science", 60); map.put("Programming", 70); System.out.println( "The map is - " + map); System.out.println( "\nCalling compute function for key Maths"); Integer newVal = map.compute("Maths", (key, oldVal) -> { return oldVal + 10; }); System.out.println("\nThe return value is " + newVal); System.out.println( "The map is - " + map); System.out.println( "\n---------------\n"); System.out.println( "Calling compute function for key Economics\n"); newVal = map.compute("Economics", (key, oldVal) -> { System.out.print("Inside BiFunction: The key is "); System.out.print(key); System.out.print(". The value is "); System.out.println(oldVal + "."); if(oldVal != null) { return oldVal + 10; } return null; }); System.out.println("\nThe return value is " + newVal); System.out.println( "The map is - " + map); } }
In the code above, we create a WeakHashMap
named map
and add some entries to it.
First, we call the compute()
method on the map
for the Maths
key.
Integer newVal = map.compute("Maths", (key, oldVal) -> { return oldVal + 10; });
The code computes a new value inside BiFunction
and updates the value associated with the Maths
key.
Then, we call the compute()
method on the map
for the Economics
key. There is no mapping associated with the Economics
key, so the map remains unchanged and returns null
.
RELATED TAGS
CONTRIBUTOR
View all Courses