实现说明
除了类 CharHistogram和函数 main,文件里再无其他定义。
stream 各阶段从左到右组合——终端操作执行之前什么都不会跑。
使用要点
- 演示输出是带标签的(
most frequent =),每个操作都会留下自己的一行标注。
常见问题
运行「字符频次直方图」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 most frequent = 标签标明各步骤。
核心语句
.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()));
代码示例
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()));
}
}