HashMap compute() Method in Java
Last Updated :
13 Dec, 2024
The compute(Key, BiFunction) method of the HashMap class in Java is used to update or compute a value for a specific key. 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 remapping function passed to compute() returns null, the mapping is removed from the HashMap (or remains absent if initially absent).
This method is useful when we need to automatically update the value for a given key in the HashMap.
Example 1: Here, we will use the compute() method to update the values in a HashMap of String keys and String values.
Java
// Update the values in a HashMap of
// String keys and String values
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Create a Map and add some values
Map<String, String> m = new HashMap<>();
m.put("Name", "Aman");
m.put("Address", "Kolkata");
// Print the map
System.out.println("Map: " + m);
// Remap the values using
// compute() method
m.compute("Name", (key, val)
-> val.concat(" Singh"));
m.compute("Address", (key, val)
-> val.concat(" West-Bengal"));
// Print new mapping
System.out.println("New Map: " + m);
}
}
OutputMap: {Address=Kolkata, Name=Aman}
New Map: {Address=Kolkata West-Bengal, Name=Aman Singh}
Explanation: In the above example, the compute() method is used to append strings to the existing values in the HashMap based on the keys "Name" and "Address".
Syntax of HashMap compute() Method
default V
compute(K key,
BiFunction<? super K, ? super V, ?
extends V> remappingFunction)
Parameters:
- key: The key for which the value is to be computed.
- remappingFunction: A function that computes the value for the specified key.
Returns: The new value associated with the specified key, or null if none.
Exceptions:
- NullPointerException: If the key is null and the map does not support null keys, or if the remappingFunction is null.
- UnsupportedOperationException: If the put operation is not supported by the map.
- ClassCastException: If the class of the key or value prevents it from being stored in this map.
- IllegalArgumentException: If some property of the key or value prevents it from being stored in this map.
Points to Remember:
- If the remapping function passed in compute returns null, the mapping is removed from Map (or remains absent if initially absent).
- If the remapping function throws an exception, the exception is re-thrown, and the current mapping is left unchanged.
- During computation, remapping function should not be able to modify this map. The compute() method can be used to update an existing value inside HashMap. For example,
Mapping to increment a int value of mapping: map.compute(key, (k, v) -> (v == null) ? 1 : v+1)
- The default implementation of this method takes no guarantee for detecting an error if the remapping function of compute() method modifies this map during computation.
Example 2: Here, we will use the compute() method to increment values in a HashMap of String keys and Integer values.
Java
// Increment the values in a HashMap of
// String keys and Integer values
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Create a Map and add some values
Map<String, Integer> m = new HashMap<>();
m.put("Key1", 12);
m.put("Key2", 15);
// Print map details
System.out.println("Map: " + m);
// Remap the values
// using compute() method
m.compute("Key1", (key, val)
-> (val == null) ? 1 : val + 1);
m.compute("Key2", (key, val)
-> (val == null) ? 1 : val + 1);
System.out.println("New Map: " + m);
}
}
OutputMap: {Key2=15, Key1=12}
New Map: {Key2=16, Key1=13}
Explanation: In the above example, the compute() method increments the integer values in the HashMap for keys "Key1" and "Key2".
Example 3: In this example, we demonstrate how NullPointerException occurs when a null
key is passed to the compute()
method.
Java
// Demonstrate NullPointerException when a
// null key is passed to compute() method
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Create a Map and add some values
Map<String, Integer> m = new HashMap<>();
m.put("Key1", 12);
m.put("Key2", 15);
// Print map details
System.out.println("Map: " + m);
try {
// Pass a null key to compute() method
m.compute(null, (key, value) -> value + 3);
System.out.println("New Map: " + m);
} catch (NullPointerException e) {
System.out.println("Exception: " + e);
}
}
}
OutputMap: {Key2=15, Key1=12}
Exception: java.lang.NullPointerException
Similar Reads
HashMap in Java
In Java, HashMap is part of the Java Collections Framework and is found in the java.util package. It provides the basic implementation of the Map interface in Java. HashMap stores data in (key, value) pairs. Each key is associated with a value, and you can access the value by using the corresponding
15+ min read
HashMap clear() Method in Java
The clear() method of the HashMap class in Java is used to remove all of the elements or mappings (key-value pairs) from a specified HashMap.Example 2: Here, we will use the clear() method to clear a HashMap of Integer keys and String values. Java// Clearing HashMap of Integer keys // and String val
2 min read
HashMap clone() Method in Java
The clone() method of the HashMap class in Java is used to create a shallow copy of the specified HashMap. The method returns a new HashMap that contains the same key-value mappings as the original HashMap.Example 1: Here, we will use the clone() method to clone a HashMap of Integer keys and String
2 min read
HashMap compute() Method in Java
The compute(Key, BiFunction) method of the HashMap class in Java is used to update or compute a value for a specific key. 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 remapping function passed to compute() returns n
4 min read
HashMap containsKey() Method in Java
The java.util.HashMap.containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.Syntax: Hash_Map.containsKey(key_element)Parameters: The method takes just one p
2 min read
Java HashMap containsValue() Method
In Java, the containsValue() method of the HashMap class is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. Example 1: This example demonstrates how the containsValue() method works when String values are mapped to integer keys.Java// Java pr
2 min read
HashMap entrySet() Method in Java
The entrySet() method of the HashMap class in Java is used to create a set view of the mappings contained in the HashMap. This method allows us to iterate over the key-value pairs in the map or convert them into a set.Example 1: Here, we will use the entrySet() method to view the mappings in a HashM
2 min read
HashMap get() Method in Java
The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. Syntax:Hash_Map.get(Object key_element)Parameter: The method takes one parameter key_el
2 min read
Java HashMap put() Method
The put() method of the Java HashMap class is used to add or update the key-value pairs in the map. If the key already exists in the map, the previous value associated with the key is replaced by the new value and If the key does not exist, the new key-value pair is added to the map.Syntax of HashMa
1 min read
Java HashMap putAll() Method
The putAll() method of the Java HashMap class is used to copy all key-value mappings from another map to the existing map. If a key exists in both maps, its value is updated with the value from the source map. Otherwise, new key-value pairs are added.Example 1: This example demonstrates copying all
2 min read