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);
}
}
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Installing Android Studio Dolphin on Mac with Apple (M1/M2) Chip - Android-Studio
- Center align text in TextView Android Programming - Android
- Change Mouse Scrolling in Mac OS X - Mac-OS-X
- Elegant CSS Box Shadows Ideas - CSS
- How to start/boot macOS in safe mode - Big Sur 11.0, Catalina 10.15, or Mojave 10.14 - MacOS
- How to uninstall GarageBand from Mac - MacOS
- Stop a Running Command on macOS Terminal - MacOS
- BSNL Broadband upgrades speed to minimum 2MBps for all users 512Kbps 1Mbps - HowTos