Java Stream Word Count Example

In order to know the count of total words in a String in Java, you can make use of the Stream API as follows,


  1. Create a String object with the text string.
  2. Now, create a Stream object using the of() static method.
  3. Pass in the string as an argument and split it using split(Regex regex) method on space regex \s.
  4. Make use of count() method from the Stream class to collect the count of words as a long value.


package org.code2care.streams;


public final class StreamWordCountExample {

    public static void main(String[] args) {

        String str = "Java is the best programming language";
        long count = Stream.of(str.split("\s+")).count();




Java Stream Word Count Code Example

Have Questions? Post them here!