Calculating frequency of each word in a sentence in java

前端 未结 19 2089
夕颜
夕颜 2020-11-29 10:15

I am writing a very basic java program that calculates frequency of each word in a sentence so far i managed to do this much

import java.io.*;

class Linked         


        
19条回答
  •  旧巷少年郎
    2020-11-29 10:53

    import java.util.*;
    
    public class WordCounter {
    
        public static void main(String[] args) {
    
            String s = "this is a this is this a this yes this is a this what it may be i do not care about this";
            String a[] = s.split(" ");
            Map words = new HashMap<>();
            for (String str : a) {
                if (words.containsKey(str)) {
                    words.put(str, 1 + words.get(str));
                } else {
                    words.put(str, 1);
                }
            }
            System.out.println(words);
        }
    }
    

    Output: {a=3, be=1, may=1, yes=1, this=7, about=1, i=1, is=3, it=1, do=1, not=1, what=1, care=1}

提交回复
热议问题