Open In App

HashMap compute() method in Java with Examples

Last Updated : 25 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The compute(Key, BiFunction) method of HashMap class allows you to update a value in HashMap. The compute() method tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). This method is used to automatically update a value for given key in HashMap.

  • 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.

Exceptions :
Non-concurrent implementations of this method should override this method and throw a ConcurrentModificationException if it is detected a change in mapping during computation. Concurrent implementations should override this method throw an IllegalStateException if it is detected a change in mapping during computation and as a result computation would never complete.

The default implementation of this method takes no guarantees about synchronization or atomic properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties.

Syntax:

default V 
       compute(K key,
             BiFunction<? super K, ? super V, ? 
                 extends V> remappingFunction)

Parameters: This method accepts two parameters:

  • key: key with which associate the value.
  • remappingFunction: function to compute the value.

Returns: This method returns new value associated with the specified key, or null if none.

Exception: This method throws:

  • NullPointerException: if the key is null and this map does not support null keys, or the remappingFunction is null.
  • UnsupportedOperationException: if the put operation is not supported by this 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.

Below programs illustrate the compute(Key, BiFunction) method:

Program 1:




// Java program to demonstrate
// compute(Key, BiFunction) method.
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // Create a Map and add some values
        Map<String, String> map = new HashMap<>();
        map.put("Name", "Aman");
        map.put("Address", "Kolkata");
  
        // Print the map
        System.out.println("Map: " + map);
  
        // remap the values using compute() method
        map.compute("Name", (key, val)
                                -> val.concat(" Singh"));
        map.compute("Address", (key, val)
                                   -> val.concat(" West-Bengal"));
  
        // print new mapping
        System.out.println("New Map: " + map);
    }
}


Output:

Map: {Address=Kolkata, Name=Aman}
New Map: {Address=Kolkata West-Bengal, Name=Aman Singh}

Program 2:




// Java program to demonstrate
// compute(Key, BiFunction) method.
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // Create a Map and add some values
        Map<String, Integer> map = new HashMap<>();
        map.put("Key1", 12);
        map.put("Key2", 15);
  
        // print map details
        System.out.println("Map: " + map);
  
        // remap the values
        // using compute method
        map.compute("Key1", (key, val)
                                -> (val == null)
                                       ? 1
                                       : val + 1);
        map.compute("Key2", (key, val)
                                -> (val == null)
                                       ? 1
                                       : val + 5);
  
        // print new mapping
        System.out.println("New Map: " + map);
    }
}


Output:

Map: {Key2=15, Key1=12}
New Map: {Key2=20, Key1=13}

Program 3: To show NullPointerException




// Java program to demonstrate Exception thrown by
// compute(Key, BiFunction) method.
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // create a Map and add some values
        Map<String, Integer> map = new HashMap<>();
        map.put("Key1", 12);
        map.put("Key2", 15);
  
        // print map details
        System.out.println("Map: " + map);
  
        try {
  
            // remap the values using compute() method
            // passing null value will throw exception
            map.compute(null, (key, value)
                                  -> value + 3);
            System.out.println("New Map: " + map);
        }
        catch (NullPointerException e) {
  
            System.out.println("Exception: " + e);
        }
    }
}


Output:

Map: {Key2=15, Key1=12}
Exception: java.lang.NullPointerException

References: https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html#compute(K, java.util.function.BiFunction)



Previous Article
Next Article

Similar Reads

How to Copy One HashMap to Another HashMap in Java?
HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass
4 min read
Converting Integer-String HashMap to String-Array-Integer HashMap in Java
Efficient Conversion of a HashMap&lt;Integer, String&gt; into another HashMap&lt;String, Integer[]&gt; involves organizing integer keys based on their corresponding string values. Here's a concise and efficient Java method to accomplish this transformation, focusing on clear and straightforward implementation. Step-by-Step Implementation of Convers
3 min read
HashMap computeIfAbsent() method in Java with Examples
The computeIfAbsent(Key, Function) method of HashMap class is used to compute the value for a given key using the given mapping function. Store the computed value for the key in Hashmap if the key is not already associated with a value (or is mapped to null) else null. Syntax: public V computeIfAbsent(K key, Function&lt;? super K, ? extends V&gt; r
2 min read
HashMap replace(key, oldValue, newValue) method in Java with Examples
The replace(K key, V oldValue, V newValue) method of Map interface, implemented by HashMap class is used to replace the old value of the specified key only if the key is previously mapped with the specified old value. Syntax: default boolean replace(K key, V oldValue, V newValue) Parameters: This method accepts three parameters : key: which is the
3 min read
HashMap replace(key, value) method in Java with Examples
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Syntax: public V replace(K key, V value) Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced. value:
3 min read
HashMap putIfAbsent(key, value) method in Java with Examples
The putIfAbsent(K key, V value) method of HashMap class is used to map the specified key with the specified value, only if no such key exists (or is mapped to null) in this HashMap instance. Syntax: public V putIfAbsent(K key, V value)Parameters: This method accepts two parameters: key: which is the key with which provided value has to be mapped.va
3 min read
HashMap forEach(BiConsumer) method in Java with Examples
The forEach(BiConsumer) method of HashMap class perform the BiConsumer operation on each entry of hashmap until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of the key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until a
3 min read
HashMap merge(key, value, BiFunction) method in Java with Examples
The merge(Key, Value, BiFunctional) method of the HashMap class is used to combine multiple mapped values for a key using the given mapping function. A bucket is actually an index of the array, that array is called a table in HashMap implementation. So table[0] is referred to as bucket0, table[1] as bucket1, and so on. If the key is not present or
3 min read
HashMap getOrDefault(key, defaultValue) method in Java with Examples
The getOrDefault(Object key, V defaultValue) method of Map interface, implemented by HashMap class is used to get the value mapped with specified key. If no value is mapped with the provided key then the default value is returned. Syntax: default V getOrDefault(Object key, V defaultValue) Parameters: This method accepts two parameters: key: which i
2 min read
HashMap computeIfPresent(key, BiFunction) method in Java with Examples
The computeIfPresent(Key, BiFunction) method of HashMap class which allows you to compute value of a mapping for specified key if key is already associated with a value (or is mapped to null). If mapping function of this method returns null, the mapping is removed. If the remapping function throws an exception, the exception is rethrown, and the ma
2 min read
Practice Tags :