Java TreeMap merge() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

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.

Java
TreeMap<String, Integer> counts = new TreeMap<>();
counts.merge("be", 1, Integer::sum);   // be=1
counts.merge("be", 1, Integer::sum);   // be=2
CallWhat it does
map.merge(k, 1, Integer::sum)Counts occurrences.
map.merge(k, s, (a, b) -> a + ", " + b)Joins strings.
map.merge(k, v, (a, b) -> null)Removes k if it exists, otherwise stores v.

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

ParameterDescription
key (K)The key to update. Not null under natural ordering.
value (V)The value to store or combine. Must not be null.
remappingFunctionBiFunction combining old and new value; returning null removes the key.

Return Value

Return ValueDescription
VThe value now stored for the key.
nullThe function returned null and the key was removed.

Compare with Similar Methods

Value-building methods compared:

MethodHow it differs
compute(k, f)Gets the key and the old value (maybe null); you handle both cases.
computeIfAbsent(k, f)Creates a value only for missing keys.
putAll(m)Overwrites instead of combining.
HashMap.mergeSame counters, but printed in hash order.

Java Examples

Example 1 — Count Words in Alphabetical Order

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());
    }
}

How It Works

  1. First sighting stores 1. When a word is not yet a key, merge simply puts the value 1 and does not call Integer::sum.
  2. Repeats add up. The second "to" and the second "be" find a value of 1, so Integer.sum(1, 1) stores 2.
  3. 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);
    }
}

How It Works

  1. First sale subtracts. balcony holds 2, the function gets (2, 1) and returns 1, which is stored and returned.
  2. Second sale hits zero. Now 1 - 1 is 0, so the lambda returns null; merge removes balcony and returns null.
  3. 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));
    }
}

How It Works

  1. Old value first. For Tue the function receives ("Art", "Music") and returns "Art, Music", so lessons keep their arrival order within a day.
  2. Single lessons stay plain. Wed gets only Chess, so the function never runs for it and no comma is added.
  3. 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.

Next: navigableKeySet()

A live NavigableSet of keys with floor, ceiling, and ranges.

navigableKeySet() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful