How to count the number of occurrences of each word?

前端 未结 6 1513
梦如初夏
梦如初夏 2020-12-21 05:32

If I have an article in English, or a novel in English, and I want to count how many times each words appears, what is the fastest algorithm written in Java?

Some pe

6条回答
  •  遥遥无期
    2020-12-21 05:55

    It is actually classic word-count algorithm. Here is the solution:

    public Map wordCount(String[] strings) {
    
      Map map = new HashMap();
      int count = 0;
    
      for (String s:strings) {
    
        if (map.containsKey(s)) {
          count = map.get(s);
          map.put(s, count + 1);
        } else {
            map.put(s, 1);
        }
    
      }
      return map;
    }
    

提交回复
热议问题