How to count the number of occurrences of a given word in a list of strings using Java 8
Categories: Java 8(JDK1.8) Java Java Examples
package r4r.co.in;
import java.util.Arrays;
import java.util.List;
public class CountGivenWordInGivenArryOfStringUsingJava8Lamda {
public static void main(String[] args) {
// How to count the number of occurrences of a given word in a list of strings using Java 8
String[] input = { "Rajesh r4r", "Rajesh r4r Kumar r4r Rajesh", "r4r" };
List<String> list = Arrays.asList(input);
String str = "r4r";
long count = list.stream().flatMap(s -> Arrays.stream(s.split(" "))).filter(w -> w.equals(str)).count();
System.out.print(count);
}
}
OutPut 4