Search code examples
java-8

How to find the most frequent words in a string using java8 streams?


I have a sample string in below input format. I'm trying to fetch the most repeated word along with it's occurance count as shown in the expected output format. How can we achieve this by using java8 streams api?

Input:

"Ram is employee of ABC company, ram is from Blore, RAM! is good in algorithms."

Expected Output:

Ram -->3
is -->3

Solution

  •     String text = "Ram is employee of ABC company, ram is from Blore, RAM! is good in algorithms.";
        List<String> wordsList = Arrays.asList(text.split("[^a-zA-Z0-9]+"));
        Map<String, Long> wordFrequency = wordsList.stream().map(word -> word.toLowerCase())
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
        long maxCount = Collections.max(wordFrequency.values());
    
        Map<String, Long> maxFrequencyList = wordFrequency.entrySet().stream().filter(e -> e.getValue() == maxCount)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    
        System.out.println(maxFrequencyList);