Java Program to get frequency of words with Lambda Expression

Java 8Object Oriented ProgrammingProgramming

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}
raja
Published on 24-Apr-2019 08:53:29
Advertisements