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.
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.
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.