Calculating frequency of each word in a sentence in java

前端 未结 19 2133
夕颜
夕颜 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:57

    In Java 8, you can write this in two simple lines! In addition you can take advantage of parallel computing.

    Here's the most beautiful way to do this:

    Stream stream = Stream.of(text.toLowerCase().split("\\W+")).parallel();
    
    Map wordFreq = stream
         .collect(Collectors.groupingBy(String::toString,Collectors.counting()));
    

提交回复
热议问题