Find Words with Exactly ‘K’ Vowels in a Sentence in Java

✅ 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:

  1. sentence.split(“\s+”): Splits the sentence by spaces into words.
  2. map(word -> word.replaceAll(“[^a-zA-Z]”, “”)): Removes punctuation (like ?, ., ,) from each word so only letters remain.
  3. filter(word -> countVowels(word) == k): Filters words where the number of vowels equals k (in this example, 3).
  4. forEach(System.out::println): Prints each word that satisfies the condition.
  5. 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.

✅ Sample Output (with k = 3):

Because
compare
characters
length

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *