使用单词出现次数的键将单词添加到 HashMap

Adding words to a HashMap with a key of how many times they appear

我正在编写一个 Java 程序,它将网站上的所有单词添加到 HashMap 中,然后为它们分配一个键,表示它们在页面上出现的次数。例如,如果我 运行 在只有单词 "hello, java, coffee, java" 的页面上,输出将是

Java:2 咖啡 : 1 你好:1

这也会忽略某些我不想包含的词。这是我目前所拥有的。

Map<String, Integer> found = new HashMap<>(); // (word,frequency)
Matcher match = Pattern.compile(word_pattern).matcher(content);

while (match.find()) {

  // Get the net word in lowercase
  String word = match.group().toLowerCase();

  //If not the set of words to ignore, add to the found Map
  if(!ignore.contains(word))
      found.put(word,       );  
  }

 System.out.println(found);

}

第二个参数,一个int,我认为应该在我将单词添加到HashMap 之前计算出来。

found.put(word,  int   );  

但我不确定如何在保持 O(nlogn) 时间的情况下准确地累加单词的出现次数。

试试这个:

if(!found.containsKey(word)){
    found.put(word, 1);
}else{
    found.put(word, found.get(word) + 1);
}

这看起来确实像一个作业,所以我会指出正确的方向而不是给出明确的代码。

当你处理一个词的时候,你需要查看HashMap,看它是否已经存在。如果是,则将当前计数加一并更新地图。如果它不在地图中,则将其添加为 1。

如果你有 Java 8 个,你可以这样做:

found.merge(word, 1, Integer::sum);