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

Java中如何获取ArrayList中每个单词的首字母和尾字母的出现次数

问题原因

你现有代码的遍历逻辑存在错误:循环内每次都计算result.size() - 1(即集合的最大索引值)后输出,自然只会打印重复的长度相关数值,没有实际取到集合里存储的每行文本内容。

实现方案

你可以用HashMap<Character, Integer>分别存储首字母、尾字母的出现次数,实现逻辑如下:

  • 遍历ArrayList中存储的每一个字符串,先判断字符串非空再处理,避免触发索引越界异常
  • 取字符串第一个字符str.charAt(0)作为首字母,更新首字母统计Map的计数
  • 取字符串最后一个字符str.charAt(str.length() - 1)作为尾字母,更新尾字母统计Map的计数
  • 遍历结束后输出两个统计Map的结果即可

修改后的完整代码

public static void ReadKeyWordsFile() {
    try {
        ArrayList<String> result = new ArrayList<>();
        File file1 = new File("./files/kywrdsOdd.txt");
        if(file1.length() == 0){
            System.out.println("The file is empty");
            return;
        }
        Scanner scan = new Scanner(file1);
        while (scan.hasNextLine()){
            // trim掉前后空白再存入,避免空行、首尾空格干扰统计结果
            String line = scan.nextLine().trim();
            if(!line.isEmpty()){
                result.add(line);
            }
        }
        scan.close();

        // 定义两个Map分别统计首字母、尾字母出现次数
        HashMap<Character, Integer> firstCharCount = new HashMap<>();
        HashMap<Character, Integer> lastCharCount = new HashMap<>();

        // 遍历集合里的每个单词
        for (String word : result) {
            // 统计首字母
            char firstChar = word.charAt(0);
            firstCharCount.put(firstChar, firstCharCount.getOrDefault(firstChar, 0) + 1);

            // 统计尾字母
            char lastChar = word.charAt(word.length() - 1);
            lastCharCount.put(lastChar, lastCharCount.getOrDefault(lastChar, 0) + 1);
        }

        // 输出统计结果
        System.out.println("首字母出现次数统计:" + firstCharCount);
        System.out.println("尾字母出现次数统计:" + lastCharCount);

    } catch (FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
    }
}

补充说明

  • 如果需要不区分大小写统计,取字符时统一转成大写Character.toUpperCase(firstChar)或者小写Character.toLowerCase(firstChar)即可
  • 代码中使用的getOrDefault是Java 8及以上版本的API,如果你使用更低版本的JDK,替换为先判断key是否存在再赋值的逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:45:01