Count vowels and consonants

The problem

Assume letters A, E, I, O, and U as the vowels. Write a program that prompts the user to enter a string and displays the number of vowels and number of consonants in the string.

Breaking it down

Once the input has been captured from the user, we can convert the String into a Instream by calling phrase.chars(). Next using a IntPredicate that checks if character is a vowel we filter the stream and count the number of vowels and consonants. You will notice that we only have to create one predicate and call the predicate.negate() which will return the opposite value of the predicate.

public static void main(String[] args) {

    Scanner input = new Scanner(;
    System.out.print("Enter a string: ");
    String phrase = input.nextLine();


    long consonantCount = phrase.chars().filter(vowel.negate()).count();
    long vowelCount = phrase.chars().filter(vowel).count();

    System.out.println("Total number of consonant is " + consonantCount);
    System.out.println("Total number of vowels is " + vowelCount);


static IntPredicate vowel = new IntPredicate() {
    public boolean test(int t) {
        return t == 'a' || t == 'e' || t == 'i' || t == 'o' || t == 'u'
                || t == 'A' || t == 'E' || t == 'I' || t == 'O' || t == 'U';


Enter a string: Running down the road
Total number of consonant is 15
Total number of vowels is 6