HashMap compute() method in Java with Examples

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 atomically 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

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

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

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

Program 3: To show NullPointerException

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
        }
    }
}

chevron_right


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)



My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.