Finding repeated words on a string and counting the repetitions

后端 未结 29 887
梦谈多话
梦谈多话 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:14

    Use Function.identity() inside Collectors.groupingBy and store everything in a MAP.

    String a  = "Gini Gina Gina Gina Gina Protijayi Protijayi "; 
            Map map11 = Arrays.stream(a.split(" ")).collect(Collectors
                    .groupingBy(Function.identity(),Collectors.counting()));
            System.out.println(map11);
    
    // output => {Gina=4, Gini=1, Protijayi=2}
    

    In Python we can use collections.Counter()

    a = "Roopa Roopi  loves green color Roopa Roopi"
    words = a.split()
    
    wordsCount = collections.Counter(words)
    for word,count in sorted(wordsCount.items()):
        print('"%s" is repeated %d time%s.' % (word,count,"s" if count > 1 else "" ))
    

    Output :

    "Roopa" is repeated 2 times. "Roopi" is repeated 2 times. "color" is repeated 1 time. "green" is repeated 1 time. "loves" is repeated 1 time.

提交回复
热议问题