Java 8 - Map merge() method

Merge the specified value to the existing Value using the Specified function for the Specified Key.

If the Key is not present , Add an element with the new Key and Value.

Format

merge([Key],[Value],[Function([Exisiting Value],[New Value]]);

Example

strMap.merge("Key1","Value56",(v1,v2)->v1.substring(3).concat(v2));

Sample Code 1

Map<String,String> intMap = new HashMap<String,String>();
strMap.put("Key1","Value1");
strMap.put("Key2", "Value2");   
String str = strMap.merge("Key1","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints ue1Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=ue1Value56}

Sample Code 2 

Map<String,String> strMap = new HashMap<String,String>();
strMap.put("Key1","Value1");
strMap.put("Key2", "Value2");   
String str = strMap.merge("Key4","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=Value1, Key4=Value56}