merge(K, V, BiFunction): This method is available in java.util.Hashtable class of Java.
Syntax:
V java.util.Hashtable.merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
This method takes three arguments. If the specified key is not already associated with a value or is associated with null, associate it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes it if the result is null.
Parameters: Three parameters are required for this method.
key: key with which the resulting value is to be associated.
value: the non-null value to be merged with the existing value associated with the key or if no existing value or a null value is associated with the key, to be associated with the key.
remappingFunction: the remapping function to recompute a value if present.
Returns: the new value associated with the specified key, or null if no value is associated with the key.
Throws:
ConcurrentModificationException - if it is detected that the remapping function modified this map
Approach
Java
import java.util.Hashtable;import java.util.function.BiFunction;public class Hashtablemerge {public static void main(String[] args) {Hashtable<String, Integer> hashtable =new Hashtable<String, Integer>();hashtable.put("Hello", 1);hashtable.put("World", 2);String key = "Java";Integer value = 5;BiFunction<? super Integer, ? super Integer,? extends Integer> remappingFunction =(a, b) -> a + b;hashtable.merge(key, value, remappingFunction);System.out.println(hashtable);}}
Output:
{Java=5, World=2, Hello=1}
No comments:
Post a Comment