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,

Steps:

  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.

Example:

package org.code2care.streams;

import java.util.stream.Stream;

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();
        System.out.println(count);

    }

}

6


Java Stream Word Count Code Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!