Java Algorithms – Find the Count of Each Word in a String

algorithmsjava

I am in a search of a better performant algorithm to implement a program, to find the count of each word in a sentence i.e.., a String in the programming sense.

I know my algorithm is too basic and Noob. Here's my algorithm.

  1. Read the String.
  2. Tokenize the String with the delimiter, put each token in a list(ArrayList).
  3. Iterate the generated list, in each iteration compare the current string with every other string of the list, if it matches increase the count of this string.
  4. For each iteration, put the String and its count in a map.
  5. Iterate the map and display, with key as string and value as its count.

What is the best approach than this?

Best Answer

Replace steps 3 and 4 with the following

  • If string is not in the map, store it in the map with value Integer.valueOf(1)
  • If is already in the map, get the current value, increment it, and replace the mapping.
Related Topic