5. Counting vowels and consonants

The following code is for English, but depending on how many languages you are covering, the number of vowels and consonants may differ and the code should be adjusted accordingly.

The first solution to this problem requires traversing the string characters and doing the following:

  1. We need to check whether the current character is a vowel (this is convenient since we only have five pure vowels in English; other languages have more vowels, but the number is still small).
  2. If the current character is not a vowel, then check whether it sits between 'a' and 'z' (this means that the current character is a consonant).

Notice that, initially, the given String object is transformed into lowercase. This is useful to avoid comparisons with uppercase characters. For example, the comparison is accomplished only against 'a' instead of 'A' and 'a'.

The code for this solution is as follows:

private static final Set<Character> allVowels
= new HashSet(Arrays.asList('a', 'e', 'i', 'o', 'u'));

public static Pair<Integer, Integer>
countVowelsAndConsonants(String str) {

str = str.toLowerCase();
int vowels = 0;
int consonants = 0;

for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (allVowels.contains(ch)) {
vowels++;
} else if ((ch >= 'a' && ch <= 'z')) {
consonants++;
}
}

return Pair.of(vowels, consonants);
}

In Java 8 functional style, this code can be rewritten using chars() and filter():

private static final Set<Character> allVowels
= new HashSet(Arrays.asList('a', 'e', 'i', 'o', 'u'));

public static Pair<Long, Long> countVowelsAndConsonants(String str) {

str = str.toLowerCase();

long vowels = str.chars()
.filter(c -> allVowels.contains((char) c))
.count();

long consonants = str.chars()
.filter(c -> !allVowels.contains((char) c))
.filter(ch -> (ch >= 'a' && ch<= 'z'))
.count();

return Pair.of(vowels, consonants);
}

The given string is filtered accordingly and the count() terminal operation returns the result. Relying on partitioningBy() will reduce the code, as follows:

Map<Boolean, Long> result = str.chars()
.mapToObj(c -> (char) c)
.filter(ch -> (ch >= 'a' && ch <= 'z'))
.collect(partitioningBy(c -> allVowels.contains(c), counting()));

return Pair.of(result.get(true), result.get(false));

Done! Now, let's see how we can count occurrences of a certain character in a string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.232