Map Merge For Frequency Counting

Count occurrences in one pass with Map.merge: the remapping function runs only when the key is already present, so a fresh key needs no null check.

JavaData Integrity

Code

snippet
import java.util.HashMap;
import java.util.Map;

public class WordFrequency {

    public static void main(String[] args) {
        String[] words = {"deploy", "build", "deploy", "test", "deploy", "build"};

        Map<String, Integer> counts = new HashMap<>();
        for (String word : words) {
            // merge:键不存在时直接放入 value;存在时用 remapping 函数合并旧值
            counts.merge(word, 1, Integer::sum);
        }
        System.out.println(counts);

        // 同样的语义手写出来要三步:判空、放入或累加
        Map<String, Integer> manual = new HashMap<>();
        for (String word : words) {
            Integer previous = manual.get(word);
            manual.put(word, previous == null ? 1 : previous + 1);
        }
        System.out.println(counts.equals(manual));
    }
}

How it works

Structurally, expect the class WordFrequency and the function main and nothing else.

One loop does the cycling here: for (String word : words).

What to watch for

  • The toolchain alone is enough — no dependency resolution happens.

Using it

The main signature reads public static void main(String[] args)

Key statements

String[] words = {"deploy", "build", "deploy", "test", "deploy", "build"};
manual.put(word, previous == null ? 1 : previous + 1);
Map<String, Integer> counts = new HashMap<>();

Interactive Tools for This Topic

FAQ

How do you run Map Merge For Frequency Counting?
The file is self-contained: run it directly, no dependencies to install beforehand.