Java SE API
Map.merge
Insert for an absent or null mapping; otherwise combine values. A null callback result removes the mapping. Optional mutation; default method makes no atomicity guarantee.
Formal Syntax & Structure
java syntaxjava
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| key | K | Target key. |
| value | V | Non-null incoming value. |
| remappingFunction | BiFunction<? super V, ? super V, ? extends V> | Combines old and incoming values. |
Return Value
V
New value, or null if removed.
Working Example
Example Snippetjava
import java.util.*;public class Main {
public static void main(String[] args) { Map<String, Integer> counts = new TreeMap<>(); for (String word : List.of("pear", "apple", "pear", "plum")) { counts.merge(word, 1, (oldValue, added) -> oldValue + added); } for (Map.Entry<String, Integer> entry : counts.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } }}