Java HashMap - compute() Method
The java.util.HashMap.compute() method is used to update a value in the HashMap. It tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). If the function returns null, the mapping is removed (or remains absent if initially absent). If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.
Syntax
public V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
Here, K and V are the type of key and value respectively maintained by the container.
Parameters
key |
Specify the key with which the specified value is to be associated. |
remappingFunction |
Specify the function to compute a value. |
Return Value
Returns the new value associated with the specified key, or null if none.
Exception
NA.
Example:
In the example below, the java.util.HashMap.compute() method is used to update a value in the given HashMap.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a HashMap HashMap<Integer, String> MyMap = new HashMap<Integer, String>(); //populating the HashMap MyMap.put(101, "John"); MyMap.put(102, "Marry"); MyMap.put(103, "Kim"); MyMap.put(104, "Jo"); //printing the HashMap System.out.println("MyMap contains: " + MyMap); //updating value of the specified key using compute method MyMap.compute(101, (k, v) -> v.concat(" Paul")); MyMap.compute(104, (k, v) -> "Sam"); //printing the HashMap System.out.println("MyMap contains: " + MyMap); } }
The output of the above code will be:
MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo} MyMap contains: {101=John Paul, 102=Marry, 103=Kim, 104=Sam}
❮ Java.util - HashMap