The opposite of finding the number of constants in a string, this example will determine the total number of vowels within a java String using java, java 8 and guava techniques.
Straight up Java
Using straight up java we will create a method that will return true if the char passed is a vowel. Using a for loop we will iterate over each char in the String calling isVowel storing the number of occurrences in a variable called vowelCount. Finally using a junit assertion we will validate that the number of vowels from the phrase equals 5.
Java 8
Using a IntPredicate, a type of predicate introduced in java 8, will return true if the int value represents a vowel. Remember that char primitive value translates into a int value. Next we will call String.chars() which will return a java 8 IntStream where we will pass the predicate to the filter method filtering any values matching. Finally we will call the reduction operation count which return the total number of elements.
Google Guava
Using guava's CharMatcher we will call anyOf which will return a CharMatcher that matches any character present in the given character sequence. In this instance, any letter a, e, i, o, or u which represent vowels. Next calling the retainFrom will return all matching characters or all the vowels of the string.