Open In App

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 automatically update a value for given key in HashMap.

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:

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

Exception: This method throws:

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)


Article Tags :