Java Program to get frequency of words with Lambda Expression


Let’s say the following is the List −

List<String> list = Arrays.asList("Welcome", "to","the","club", "club", "the");

No, let us create a Map to get the frequency of words. Here, we are using Lambda Expression as well −

Map<String, Integer> map = list
   .parallelStream()
   .flatMap(a -> Arrays.asList(a.split(" ")).stream())
   .collect(
   Collectors.toConcurrentMap(c ->c.toLowerCase(), c -> 1,
   Integer::sum));

Example

 Live Demo

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Demo {
   public static void main(String[] args) {
      List<String> list = Arrays.asList("Welcome", "to","the","club", "club", "the");
      Map<String, Integer> map = list
         .parallelStream()
         .flatMap(a -> Arrays.asList(a.split(" ")).stream())
         .collect(
         Collectors.toConcurrentMap(c ->c.toLowerCase(), c -> 1,
         Integer::sum));
      System.out.println("Word Frequency = "+map);
   }
}

Output

Word Frequency = {the=2, club=2, to=1, welcome=1}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements