Codectionary / Developer documentation / Java

Frequency Counts with Map.merge

Combine repeated keys with a clear rule for updating their values.

What it is and why to use it

A frequency table associates each item with its count. merge supplies an initial value for a missing or null mapping and combines an existing non-null value with the supplied value. It makes the update rule explicit without a separate lookup and branch.

How it works

Integer::sum receives the old count and the incoming 1. LinkedHashMap is used here to make iteration and printed output follow first insertion order. A remapping function that returns null removes the mapping instead of storing a null value.

Common mistakes and limitations

Ordinary map merge is not a general thread-safety guarantee. Do not pass null as the supplied value. Integer counts can overflow in very large workloads; choose an appropriate numeric type and overflow policy.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

counts.merge(word, 1, Integer::sum);

Examples

Frequency Counts with Map.merge

Complete Main.java example — Java 17 or later, without preview features.

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<String, Integer> counts = new LinkedHashMap<>();
    for (String language : List.of("Java", "Ruby", "Java")) {
      counts.merge(language, 1, Integer::sum);
    }
    System.out.println(counts);
  }
}
  1. The first Java value has no mapping, so merge stores 1 without calling the sum function.
  2. Ruby is also inserted with 1. The next Java combines old count 1 with incoming value 1.
  3. The final table reports two Java occurrences and one Ruby occurrence. This is useful for counters in a small report or batch processor.
  4. Expected output: {Java=2, Ruby=1}

Best practices

  • Use an explicit ordering map when display order matters.
  • Understand that a null remapping result deletes an entry.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading