In this Answer, we’ll learn how to find the sentence with the greatest number of words in an array of sentences.
For example, let’s consider we have an array that contains the following three sentences:
“sam and john love educative”,
“We all think so too”,
“this is great thanks very much”
The output that we expect to receive is , which is the number of words in the third sentence in the array—the one with the greatest number of words in it.
The assumption that we make in the solution below is that a single space separates two words in a sentence.
The simple solution to the problem above is as follows:
import java.util.Arrays; import java.util.stream.Stream; class Main { public static int mostWordsFound(String[] sentences) { return 1 + Stream.of(sentences) .mapToInt(sentence -> (int) sentence.chars().filter(character -> character == ' ').count()) .max() .getAsInt(); } public static void main(String[] args) { String[] sentences = {"sam and john love educative", "We all think so too", "this is great thanks very much"}; int count = mostWordsFound(sentences); System.out.println("Array of sentences - " + Arrays.toString(sentences)); System.out.println("The max number of words found in any sentence is " + count); } }
mostWordsFound
. With this function, we count the number of single spaces in a sentence using the mapToInt
function. We then find out the maximum value, add one to it, and return this value.sentences
.mostWordsFound()
method on our array.sentences
array.Refer What is the Stream.mapToInt() method in Java? to learn more about
mapToInt()
.
RELATED TAGS
CONTRIBUTOR
View all Courses