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:
- Create a String object with the text string.
- Now, create a Stream object using the of() static method.
- Pass in the string as an argument and split it using split(Regex regex) method on space regex \s.
- 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);
}
}

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!