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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap