merge(K, V, BiFunction): This method is available in java.util.TreeMap class of Java.
Syntax:
String java.util.TreeMap.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 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.TreeMap;import java.util.function.BiFunction;public class TreeMapmerge {public static void main(String[] args) {TreeMap<Integer, String> treeMap =new TreeMap<Integer, String>();treeMap.put(2, "Hello");treeMap.put(11, "Java");treeMap.put(23, "Program");treeMap.put(6, "C++");treeMap.put(25, "Program");Integer key = 2;String value = " World";BiFunction<? super String, ? super String,? extends String> remappingFunction = (a, b) -> a + b;System.out.println(treeMap.merge(key,value, remappingFunction));}}
Output:
Hello World
No comments:
Post a Comment