Java 8 Program to Find and Count Vowels in a String

Learn how to find and count vowels in a string using Java 8 Streams. The program converts the input string to lowercase, filters vowel characters, prints each vowel, and counts the total number of vowels present in the string.

Code Explanation (Step-by-Step)

  • First, we convert the given input string to lowercase using the toLowerCase() method.
  • Create a List<Character> to store all vowel characters.
  • Add the vowels (a, e, i, o, u) to the list.
  • Convert the string into a stream of characters using the chars() method.
  • Use mapToObj() to convert each character from a primitive int to a Character object.
  • Use the filter() method to check whether a character is a vowel by using the contains() method of the list.
  • Print each vowel character using the forEach() method.
  • Use the count() method to calculate the total number of vowels present in the string.
  • Now print the total vowel count.
				
					import java.util.Arrays;
import java.util.List;

public class VowelCount {

    public static void main(String[] args) {

        String str = "welcome to java";
        String lowerCase = str.toLowerCase();

        List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u');

        System.out.println("Vowel characters are:");

        lowerCase.chars()
                 .mapToObj(c -> (char) c)
                 .filter(vowels::contains)
                 .forEach(System.out::println);

        long vowelCount = lowerCase.chars()
                                   .mapToObj(c -> (char) c)
                                   .filter(vowels::contains)
                                   .count();

        System.out.println("Total number of vowels is: " + vowelCount);
    }
}
				
			

Output :-
Vowel characters are :
e
o
e
o
a
a
Total number of vowel is: 6

Count the Total Number of Vowels

				
					public class VowelCount {

    public static void main(String[] args) {

        String str = "welcome to java";
        int count = 0;

        str = str.toLowerCase();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            if (ch == 'a' || ch == 'e' || ch == 'i' ||
                ch == 'o' || ch == 'u') {
                count++;
            }
        }

        System.out.println("Total number of vowels is: " + count);
    }
}
				
			

Output :-
Total number of vowels is: 6