Count consonants in string

The opposite of finding the number of vowels in a string, this example will determine the total number of consonants in a java String using straight up java 1.7 and below, java 8 and guava techniques.

Straight up Java

We will first create a method isVowel that will return true if the char matches a, e, i, o or u. Using a standard for loop we will iterate over each element in the string and if it doesn't match we will increment consonantCount variable.

boolean isVowel(char t) {
    return t == 'a' || t == 'e' || t == 'i' || t == 'o' || t == 'u'
            || t == 'A' || t == 'E' || t == 'I' || t == 'O' || t == 'U';
}

@Test
public void count_vowels_in_string_java() {

    String phrase = "Whack for my daddy-o. There's whiskey in the jar-o";

    long consonantCount = 0;
    for (int x = 0; x < phrase.length(); x++) {
        if (!isVowel(phrase.charAt(x))) {
            consonantCount++;
        }
    }

    assertEquals(38, consonantCount);
}

Java 8

Using a IntPredicate, a type of predicate introduced in java 8, will return if true the value passed matches a, e, i, or u. Next we will call String.chars() that will return a IntStream where we will pass the vowel.negate() to the filter method. Calling the negate on a predicate will reverse or return the opposite of the predicate, in this case any characters that don't match a vowel or any value that resembles a consonants. Finally we will call the java 8 reduction operation count which will return the total number of elements.

@Test
public void count_vowels_in_string_java8() {

    IntPredicate vowel = new IntPredicate() {
        @Override
        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';
        }
    };

    String phrase = "Whack for my daddy-o. There's whiskey in the jar-o";

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

    assertEquals(38, consonantCount);
}

Google Guava

We will create a guava CharMatcher that resembles a vowel and call the negate() method which return all characters that don't match a vowel, in other words consonants. We will call the countIn method which will returns the number of matching characters found in a character sequence.

@Test
public void count_vowels_in_string_guava() {

    String phrase = "Whack for my daddy-o. There's whiskey in the jar-o";

    int consonantCount = CharMatcher.anyOf("aeiou").negate()
            .countIn(phrase);

    assertEquals(38, consonantCount);
}