Character Frequency Histogram
Count per-character occurrences by turning a String into an IntStream of chars and grouping into a sorted frequency map.
Code
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharHistogram {
public static void main(String[] args) {
String sample = "mississippi";
// chars() 把字符串变成 int 流:每个元素是一个字符码点
Map<Character, Long> counts = sample.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
TreeMap::new, // TreeMap:按键排序输出
Collectors.counting()));
counts.forEach((ch, n) ->
System.out.println(ch + " x" + n));
// 最高频字符:比较 Map.Entry 的值
counts.entrySet().stream()
.max(Map.Entry.comparingByValue())
.ifPresent(e ->
System.out.println("most frequent = " + e.getKey()));
}
}How the snippet works
Character Frequency Histogram comes down to the class CharHistogram and the function main.
Stream stages compose left to right — nothing executes until the terminal operation runs.
Applying it
The demo output is labeled (most frequent =), so the printed lines read as a trace of the operations that ran.
Statements that matter
.collect(Collectors.groupingBy(
Function.identity(),
TreeMap::new, // TreeMap:按键排序输出
Collectors.counting()));
counts.entrySet().stream()
.max(Map.Entry.comparingByValue())
.ifPresent(e ->
System.out.println("most frequent = " + e.getKey()));
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
- What does Character Frequency Histogram print when run?
- Run it as a complete program — the output lines carry labels such as `most frequent =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.