Finding repeated words on a string and counting the repetitions

后端 未结 29 931
梦谈多话
梦谈多话 2021-02-05 17:49

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:

String s = \"House, House         


        
29条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 18:29

    Once you have got the words from the string it is easy. From Java 10 onwards you can try the following code:

    import java.util.Arrays;
    import java.util.stream.Collectors;
    
    public class StringFrequencyMap {
        public static void main(String... args) {
            String[] wordArray = {"House", "House", "House", "Dog", "Dog", "Dog", "Dog"};
            var freq = Arrays.stream(wordArray)
                             .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
            System.out.println(freq);
        }
    }
    

    Output:

    {House=3, Dog=4}
    

提交回复
热议问题