HashMap replaceAll(BiFunction) method in Java with Examples

The replaceAll(BiFunction) method of HashMap class replaces each value with the result of applying the given function(performs a certain operation) on the corresponding value. This process continues in the same manner until all the entries have been processed or until an exception is thrown by the function. It rethrows exceptions thrown by the replacement function.

Syntax:

default void replaceAll(BiFunction<K, V> function)

Parameter:



  • BiFunction: function to do the operation on value for each entry.

Return value: replaces calculated values in place and the method returns nothing

Exceptions:

  • ClassCastException: thrown to indicate that the replacement class has attempted to cast an object to a subclass which is of the type not acceptable by this map.
    Example: When one tries to cast an Integer to a String, String is not being a subclass of Integer, a ClassCastException will be thrown.
  • ConcurrentModificationException: occurs when an object is tried to be modified or removed simultaneously when it is iterated over.
    Example: It is not permissible for a thread(independent path of execution within a program) to modify a Collection when some other thread is iterating over it. The reason why this happens is the result of the above operation becomes undefined.
  • IllegalArgumentException (optional): when some property of the replacement value has been passed an illegal or inappropriate argument and so prevents it from being stored in this map.
    Example: if a method requires a non-empty string as a parameter and the input string equals to null, the IllegalArgumentException is thrown.
  • NullPointerException (optional): when the given function points to null or newValue has not been initialized yet and hence refers to null it throws a NullPointerException.
    Example: Calling the instance method of a null object.
  • UnsupportedOperationException (Optional): thrown to indicate that the requested operation is not supported by this map.
    Example: In ArraysList class if we use add or remove method UnsupportedOperationException is thrown.

Below programs illustrate the merge(Key, Value, BiFunctional) method:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// replaceAll(BiFunction) method.
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // create a HashMap having some entries
        HashMap<String, Integer>
            map1 = new HashMap<>();
        map1.put("key1", 1);
        map1.put("key2", 2);
        map1.put("key3", 3);
        map1.put("key4", 4);
  
        // print map details
        System.out.println("HashMap1: "
                           + map1.toString());
  
        // replace oldValue with square of oldValue
        // using replaceAll method
        map1.replaceAll((key, oldValue)
                            -> oldValue * oldValue);
  
        // print new mapping
        System.out.println("New HashMap: "
                           + map1);
    }
}

chevron_right


Output:

HashMap1: {key1=1, key2=2, key3=3, key4=4}
New HashMap: {key1=1, key2=4, key3=9, key4=16}

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// replaceAll(BiFunction) method.
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // create a HashMap having
        // record of the year of birth
        HashMap<String, Integer>
            map1 = new HashMap<>();
        map1.put("Tushar", 2000);
        map1.put("Anushka", 2001);
        map1.put("Sanskriti", 2003);
        map1.put("Anuj", 2002);
  
        // print map details
        System.out.println("HashMap1: "
                           + map1.toString());
  
        // replace yearOfBirth with current age
        // using replaceAll method
        map1.replaceAll((key, yearOfBirth)
                            -> 2019 - yearOfBirth);
  
        // print new mapping
        System.out.println("New HashMap: "
                           + map1);
    }
}

chevron_right


Output:

HashMap1: {Sanskriti=2003, Anushka=2001, Tushar=2000, Anuj=2002}
New HashMap: {Sanskriti=16, Anushka=18, Tushar=19, Anuj=17}

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/Map.html#replaceAll(java.util.function.BiFunction)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.