Word Frequency Count in Java 8

By Yashwant Chavan, Views 9662, Last updated on 04-Nov-2016

In this tutorial you will how to find out word frequency count using Java 8 Stream api.

tags java

Refer below steps.

  • Define String variable for which you want to calculate the frequency of word.
  • Split all the words (w -> w.split("\\s+")) and convert it into List<String>.
  • Use Collectors.toMap() method to accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.
  • Define keyMapper function w -> w.toLowerCase() for toMap() method.
  • Define valueMapper function w -> 1 for toMap() method.
  • Define mergeFunction Integer::sum for toMap() method.
  • Print the result in the form of keys and values(Map<String, Integer>)

Word Frequency Count

package com.technicalkeeda.app;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8WordFrequencyCount {

    public static void main(String[] args) {

        String str = "Lorem adipising ipsum dolor sit Lorem amet Consectetur adipising elit Lorem ipsum dolor";

        List <String> list = Stream.of(str).map(w -> w.split("\\s+")).flatMap(Arrays::stream)
            .collect(Collectors.toList());

        Map <String, Integer > wordCounter = list.stream()
            .collect(Collectors.toMap(w -> w.toLowerCase(), w -> 1, Integer::sum));

        System.out.println(wordCounter);

    }
}

output

{adipising=2, dolor=2, lorem=3, amet=1, ipsum=2, elit=1, consectetur=1, sit=1}
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]