关于#java Map#的问题

统计一段文章中每个单词出现的次数,不考虑标点符号
例如:String speak = “this is a book this is an elephont”;
(代码实现)

用HashMap实现
可以参考一下这个

import java.util.*;

public class WordCount {
    public static void main(String[] args) {
        String speak = "this is a book this is an elephant";
        // 将字符串按照空格分割成数组
        String[] words = speak.split(" ");
        // 创建HashMap用于存储单词出现的次数
        HashMap<String, Integer> map = new HashMap<>();
        // 遍历单词数组,统计每个单词出现的次数
        for (String word : words) {
            // 去除单词中的标点符号
            word = word.replaceAll("[^a-zA-Z0-9]", "");
            if (word.length() > 0) { // 忽略空字符串
                if (map.containsKey(word)) {
                    map.put(word, map.get(word) + 1);
                } else {
                    map.put(word, 1);
                }
            }
        }
        // 输出单词出现次数
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}