How to count words in java

后端 未结 6 1693
心在旅途
心在旅途 2020-12-06 21:00

I am looking for an algorithm, hint or any source code that can solve my following problem.

I have a folder it contains many text files. I read them and store all te

6条回答
  •  粉色の甜心
    2020-12-06 21:40

    This code will return all distinct words as a key and count as a value of each words found in a sentence. Just create a String object as a input from file or command prompt and pass it in below method.

    public Map getWordsWithCount(String sentances)
    {
        Map wordsWithCount = new HashMap();
    
        String[] words = sentances.split(" ");
        for (String word : words)
        {
            if(wordsWithCount.containsKey(word))
            {
                wordsWithCount.put(word, wordsWithCount.get(word)+1);
            }
            else
            {
                wordsWithCount.put(word, 1);
            }
    
        }
    
        return wordsWithCount;
    
    }
    

提交回复
热议问题