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

一世执手 提交于 2019-12-13 07:17:36

问题


I'm writing a Java program which adds all of the words on a website into a HashMap, and then assigns them a key of how many times they appear on the page. For instance, if I ran it on a page with only the words "hello, java, coffee, java", the output would be

Java : 2 Coffee : 1 Hello : 1

This also ignores certain words that I don't want included. Here's what I have so far.

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);

}

The second parameter, an int, I assume should be calculated before I add the word to the HashMap.

found.put(word,  int   );  

But I'm unsure of how exactly to add up the occurrences of a word while keeping O(nlogn) time.


回答1:


This really looks like an assignment so I'll point in the right direction rather than give explicit code.

When you process a word, you need to look in the HashMap to see if it is already there. If it is, add one to the current count and update the Map. If it's not present in the Map, add it with a count of 1.




回答2:


If you have Java 8, you can do this:

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



回答3:


Try this:

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


来源:https://stackoverflow.com/questions/36871699/adding-words-to-a-hashmap-with-a-key-of-how-many-times-they-appear

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!