Skip to content
Related Articles

Related Articles

HashMap compute() method in Java with Examples
  • Last Updated : 29 Oct, 2018

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:




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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :