Count vowels in string

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.

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 = "whIskey tango fox";
    
    long vowelCount = 0;
    for (int x = 0; x < phrase.length(); x ++) {
        if (isVowel(phrase.charAt(x))) {
            vowelCount ++;
        }
    }

    assertEquals(5, vowelCount);
}

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.

@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 = "whIskey tango fox";

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

    assertEquals(5, vowelCount);

}

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.

@Test
public void count_vowels_in_string_guava() {

    String phrase = "whiskey tango fox";

    int vowelCount = CharMatcher.anyOf("aeiou").countIn(phrase);
    
    assertEquals(5, vowelCount);
}