How to count the number of occurrences of each word?

前端 未结 6 1512
梦如初夏
梦如初夏 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:59

    If i were you, I would use one of the implementations of a map, like a hashmap. Then as you loop through each word if it already exists just increment the int by one, otherwise add it into the map. At the end you can pull out all of the words, or query it based on a specific word to get the count.

    If order is important to you, you could try a SortedMap to be able to pring them out in alphabetical order.

    Hope that helps!

提交回复
热议问题