How To Count Each Word Occurrence Of Input String Using Java

 Posted On  | Yashwant Chavan 

Recently I had given interview in one of the reputed organization, An interviewer gave me small assignment to count each word occurrence of input text. Actually he want to check which collection i am using while storing the data.

Java HashMap

Use of Java HashMap is to store data in the form of Key Value pair. Here Key is nothing but each word and Value word occurrence count.


import java.util.HashMap;
import java.util.Map;

public class CountWordTest {
    public static void main(String[] args) {
        CountWordTest countWordTest = new CountWordTest();
        countWordTest.countWords("find spring tutorial, java tutorial how to java articles spring articles and may more");

    public void countWords(String input) {
        Map <String, String> map = new HashMap <String, String> ();

        if (input != null) {
            String[] separatedWords = input.split(" ");
            for (String str: separatedWords) {
                if (map.containsKey(str)) {
                    int count = Integer.parseInt(map.get(str));
                    map.put(str, String.valueOf(count + 1));
                } else {
                    map.put(str, "1");

        System.out.println("Count :- " + map);



Count :- {to=1, may=1, more=1, articles=2, how=1, tutorial=1, java=2, 
tutorial,=1, spring=2, find=1, and=1}

© 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0289 seconds.