You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计ArrayList<String>各元素中"the"的出现次数?修正遍历问题

问题分析与修复方案

咱们先拆解下你的代码为啥只遍历了部分元素,还没法正确统计所有元素里的"the"次数:

核心问题点

  • 只遍历了中间元素:你用了comments.subList(1, comments.size() - 1),这个方法会返回原列表中从索引1(包含)到comments.size()-1(不包含)的子列表,直接跳过了第一个和最后一个元素,这就是你说的“仅遍历部分元素”的根源。
  • 提前返回导致遍历中断:在循环内部,你处理完第一个元素后就直接return count了,函数直接结束,后面的元素根本没机会被处理。而且每次循环都把count重置为0,就算没提前返回,最终也只能拿到最后一个元素的统计数,不是总和。

修复后的代码

下面是修正后的版本,能遍历所有元素并统计总次数:

public static int counter(List<String> comments) {
    String targetWord = "the";
    int totalCount = 0; // 把总计数器放在循环外面,累计所有元素的次数

    // 遍历整个列表,不要用subList截断
    for (String comment : comments) {
        // 用\\s+匹配任意空白字符(空格、制表符、多个连续空格等),拆分更准确
        String[] words = comment.split("\\s+");
        for (String word : words) {
            // 去掉单词前后的标点,避免"the,""the."这类情况被漏统计
            String cleanWord = word.replaceAll("[^a-zA-Z]", "");
            if (targetWord.equals(cleanWord)) {
                totalCount++;
            }
        }
        System.out.println(comment);
    }

    return totalCount;
}

额外优化建议

  1. 忽略大小写统计:如果需要把"The""THE"这类变体也算进去,把判断条件改成targetWord.equalsIgnoreCase(cleanWord)。
  2. 更简洁的流式写法(Java 8+):如果想用更现代的方式实现,可以用Stream API简化代码:
public static int counter(List<String> comments) {
    String target = "the";
    return comments.stream()
            .flatMap(comment -> Arrays.stream(comment.split("\\s+")))
            .map(word -> word.replaceAll("[^a-zA-Z]", ""))
            .filter(target::equals)
            .mapToInt(e -> 1)
            .sum();
}

内容的提问来源于stack exchange,提问作者dinosaurjohnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:14:47