Java : Counting frequency of word in a string using Map

Use a Map to map Map<String,Integer> the words with frequency.

String SPACE =" ";
String [] words = input.split(SPACE);
Map<String,Integer> frequency = new HashMap<String,Integer>();
for (String word:words){
    Integer f = frequency.get(word);
    frequency.put(word,f+1);
}

Then you can find out for a particular word with:
frequency.get(word);

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...