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.
Code
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
Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Word Frequency CounterCount word occurrences in text with Unicode-aware tokenization, optional lowercasing, and a ranked frequency table.
FAQ
- How do you run Map Merge For Frequency Counting?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.