In Java, merge(key, value, function) stores value when key is missing (or mapped to null). When the key already has a value, it calls function.apply(oldValue, value) and stores the result instead.
If the function returns null, the key is removed. This makes merge the shortest way to keep counters, totals, or joined strings, and with a TreeMap the results come out in sorted key order.
An instance method of java.util.TreeMap, added in Java 8 as part of the Map interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe. TreeMap has its own implementation since Java 15 (earlier versions use the Map default); the behaviour is the same.
Syntax
Pass the key, the value to add, and how to combine old and new.
The function only runs when the key already has a non-null value. Its first argument is the old value, the second is the value you passed in.
Library declarations
Java
// java.util.TreeMap<K, V>
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
// Default method of Map<K, V> since Java 8; TreeMap overrides it since Java 15
Parameters
Parameter
Description
key (K)
The key to update. Not null under natural ordering.
value (V)
The value to store or combine. Must not be null.
remappingFunction
BiFunction combining old and new value; returning null removes the key.
Return Value
Return Value
Description
V
The value now stored for the key.
null
The function returned null and the key was removed.
Every word adds 1; the TreeMap lists the result alphabetically.
Java
import java.util.TreeMap;
public class TreeMapMergeWordCount {
public static void main(String[] args) {
String text = "to be or not to be that is the question";
TreeMap<String, Integer> counts = new TreeMap<>();
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts);
System.out.println("distinct words: " + counts.size());
}
}
First sighting stores 1. When a word is not yet a key, merge simply puts the value 1 and does not call Integer::sum.
Repeats add up. The second "to" and the second "be" find a value of 1, so Integer.sum(1, 1) stores 2.
A sorted frequency table. Ten words collapse into eight keys, printed from be to to without any extra sorting step.
Example 2 — Remove a Ticket Type When It Sells Out
The function returns null when no balcony seats are left, which deletes the key.
Java
import java.util.TreeMap;
public class TreeMapMergeSellOut {
public static void main(String[] args) {
TreeMap<String, Integer> tickets = new TreeMap<>();
tickets.put("balcony", 2);
tickets.put("stalls", 5);
for (int sale = 1; sale <= 2; sale++) {
Integer left = tickets.merge("balcony", 1, (have, sold) -> have - sold == 0 ? null : have - sold);
System.out.println("sale " + sale + ", balcony left: " + left);
}
System.out.println(tickets);
}
}
Output
sale 1, balcony left: 1
sale 2, balcony left: null
{stalls=5}
How It Works
First sale subtracts. balcony holds 2, the function gets (2, 1) and returns 1, which is stored and returned.
Second sale hits zero. Now 1 - 1 is 0, so the lambda returns null; merge removes balcony and returns null.
Only stalls remain. The printed map no longer lists balcony at all, which is cleaner than keeping a key with 0.
Example 3 — Collect Lessons Per Day Into One String
Lessons arrive in any order; merge appends each one to its day.
Java
import java.util.TreeMap;
public class TreeMapMergeTimetable {
public static void main(String[] args) {
String[][] lessons = {{"Tue", "Art"}, {"Mon", "Math"}, {"Tue", "Music"}, {"Mon", "Physics"}, {"Wed", "Chess"}};
TreeMap<String, String> week = new TreeMap<>();
for (String[] lesson : lessons) {
week.merge(lesson[0], lesson[1], (old, add) -> old + ", " + add);
}
week.forEach((day, subjects) -> System.out.println(day + ": " + subjects));
}
}
Output
Mon: Math, Physics
Tue: Art, Music
Wed: Chess
How It Works
Old value first. For Tue the function receives ("Art", "Music") and returns "Art, Music", so lessons keep their arrival order within a day.
Single lessons stay plain. Wed gets only Chess, so the function never runs for it and no comma is added.
Alphabetical, not calendar. Mon, Tue, Wed happen to be in alphabetical order; add Thu and it would print before Tue. Use numbered keys or a custom Comparator for real weekday order.
Frequently Asked Questions
The new value stored for the key, or null if the remapping function returned null and the key was removed.
Only when the key already has a non-null value. For a new key, or one mapped to null, the given value is stored directly.
Call counts.merge(word, 1, Integer::sum) for each word. The TreeMap keeps the words in alphabetical order.
No. merge throws NullPointerException if the value or the function is null.
merge receives the old value and your new value and is never called for absent keys; compute receives the key and the old value, which may be null.