← 中文资源

简体中文版本

用 Stream 统计高频词

把多行文本拆成小写单词,用 groupingBy 与 counting 统计词频,再按次数降序、单词升序排序并取前三名。

阅读英文原文

题目

编写 topWords(List lines, int limit),统计所有行中出现频率最高的单词。全部转为小写,按任意非字母字符序列拆分,忽略长度小于 3 的单词,limit 必须为正数。结果按出现次数降序排列,次数相同时按单词自然顺序升序,返回包含单词和 Long 计数的条目列表。

解题思路

flatMap 把每一行映射成单词流,toLowerCase(Locale.ROOT) 统一大小写,split(“[^a-z]+”) 一次性去掉标点、数字和空白。filter 去掉过短单词以及分隔符产生的空串。Collectors.groupingBy(Function.identity(), Collectors.counting()) 在单次遍历中构建词频映射。随后对 entrySet 排序:先用 Long.compare 比较计数并取反实现降序,计数相同再调用 String.compareTo 实现字母升序。手写比较器可以避免泛型推断的歧义,也让平局规则一目了然。排序完成后才 limit(3),保证被截掉的是排名靠后的词。

参考实现要点

  1. Locale.ROOT 让大小写转换在不同语言环境下保持一致。
  2. 取反实现降序时用 Long.compare,避免直接相减导致溢出。
  3. 先排序后 limit,顺序反过来会得到错误的候选集合。
  4. 参数校验放在流处理之前,非法 limit 直接抛出异常。

常见错误

按空格拆分会把 dog. 和 dog 当成两个词,必须使用非字母字符类。计数用 Integer 可能在大文本下溢出,应使用 counting 返回的 Long。只按次数排序时,并列词的顺序会随 HashMap 遍历顺序变化。忘记过滤空串会让空字符串进入统计,虽然长度过滤通常会顺带排除它。

验证方式

运行 main 方法,应输出 the 4、dog 2、fox 2。构造所有词频都为 1 的输入,确认按字母序取前三。加入 fox. 与 fox, 等带标点的形式,确认合并为同一个词。传入 limit 为 0 或负数,确认抛出 IllegalArgumentException 而不是返回空列表。

代码示例

import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class TopWords {
    static List<Map.Entry<String, Long>> topWords(List<String> lines, int limit) {
        if (limit < 1) {
            throw new IllegalArgumentException("limit must be positive");
        }

        Map<String, Long> counts = lines.stream()
                .flatMap(line -> Arrays.stream(
                        line.toLowerCase(Locale.ROOT).split("[^a-z]+")))
                .filter(word -> word.length() >= 3)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()));

        return counts.entrySet().stream()
                .sorted((a, b) -> {
                    int byCount = Long.compare(b.getValue(), a.getValue());
                    if (byCount != 0) {
                        return byCount;
                    }
                    return a.getKey().compareTo(b.getKey());
                })
                .limit(limit)
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<String> lines = List.of(
                "The quick brown fox jumps over the lazy dog.",
                "The dog barks; the fox runs.");
        topWords(lines, 3).forEach(entry ->
                System.out.println(entry.getKey() + " " + entry.getValue()));
    }
}