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

如何实例化Map,通过split分割单词并遍历数组实现词频统计

单词计数的Map实现方案

你的需求是实现单词出现次数的统计,核心逻辑方向正确,但提供的代码存在语法错误和方法调用问题,以下是修正后的完整实现及说明:

完整可运行代码

import java.util.HashMap;
import java.util.Map;

public class WordCounter {
    public static Map<String, Integer> countWords(String input) {
        // 实例化HashMap,注意类名无空格,Java7+可用菱形语法简化泛型声明
        Map<String, Integer> map = new HashMap<>();
        // 分割字符串为单词数组,用\\s+匹配任意空白字符,避免连续空格产生空串
        String[] stringArray = input.split("\\s+");
        
        // 遍历单词数组统计次数
        for (String s : stringArray) {
            // 判断当前单词是否已作为键存在于Map中
            if (map.containsKey(s)) {
                // 已存在则计数加1
                map.put(s, map.get(s) + 1);
            } else {
                // 不存在则新增键值对,初始计数为1
                map.put(s, 1);
            }
        }
        
        return map;
    }

    public static void main(String[] args) {
        // 测试示例
        String testStr = "hello world hello java world";
        Map<String, Integer> result = countWords(testStr);
        System.out.println(result); // 输出:{hello=2, world=2, java=1}
    }
}

关键修正与优化说明

  • 类名与变量名规范:你写的Hash Map是错误写法,正确类名为HashMap;string Array不符合Java驼峰命名规则,应改为stringArray
  • 存在性判断方法:不存在containerization这个方法,判断Map中是否包含指定键需使用map.containsKey(s)
  • 分割逻辑优化:若直接用split(" "),输入有连续空格时会生成空字符串,改用split("\\s+")可匹配任意数量的空白字符(空格、制表符等),避免统计无效空串

Java 8+ 简化写法

如果使用Java 8及以上版本,可借助Map.merge方法一行完成计数逻辑,让代码更简洁:

import java.util.HashMap;
import java.util.Map;

public class WordCounter {
    public static Map<String, Integer> countWords(String input) {
        Map<String, Integer> map = new HashMap<>();
        String[] stringArray = input.split("\\s+");
        
        for (String s : stringArray) {
            // merge方法:键不存在则设为1,存在则将旧值加1
            map.merge(s, 1, Integer::sum);
        }
        
        return map;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:22:21