Character Frequency Histogram

Count per-character occurrences by turning a String into an IntStream of chars and grouping into a sorted frequency map.

JavaData Integrity

Code

snippet
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

FAQ

What does Character Frequency Histogram print when run?
Run it as a complete program — the output lines carry labels such as `most frequent =`.