In this tutorial, we will see “How to count number of words in a String using Java 8?”
Count number of words in a String in Java 8
Java 8 – How to Count the number of Words in a String? Share on X
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /** * Count Words in a String using Java 8 Stream * @author Deepak Verma * */ import java.util.Arrays; import java.util.stream.Stream; public class Count_Words_In_A_String_Java8_Example { public static void main(String[] args) { String inputString = "Learn how to Count the number of Words in a String"; wordsCounter(inputString); } public static void wordsCounter(String inputString) { Stream<String> streamOfWords = Arrays.stream(inputString.split("\\s+")); long count = streamOfWords.count(); System.out.println("The Number of words in the provided string: " + count); } } |
Output:
1 | The Number of words in the provided string: 11 |
check if text or string present in a file using java 8
In the above example, It first uses the split
method to split the provided string into an array of strings using a regular expression that matches the whitespace as the delimiter. Then, the Arrays.stream()
method is used to create a stream of the final array of strings. After that, count()
method is used to get the number of elements in the stream. And, at last, it uses the sysout method to print the count of the words in the string.
Count number of words in a String in Java 8
skip method java 8 stream
Java 8 – How to Count the number of Words in a String? Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: