A sister example of counting the number of instances of uppercase letters this example will count the number of lower case letters within a phrase using java 8 and guava.
Java 8
Using java 8 we will calculate the number of lower case letters. Starting with a String we will call chars() which will return a IntStream. Next we will filter out any lower case letters by passing a java 8 predicate Character::isLowerCase. Finally we will use the stream terminal operation count to find the total number of instances.
@Test
public void count_upper_case_letters_java8() {
String catInTheHat = "The Cat in the Hat Knows a Lot About That!";
long count = catInTheHat.chars().filter(Character::isLowerCase).count();
assertEquals(25, count);
}
Google Guava
This snippet will use guava to determine the total number of lower case letters in a String. You can think of CharMatcher as a set of characters so when we use CharMatcher.JAVALOWERCASE it means any lower case letters. The retainFrom function will remove all non-matching characters or all non lower case values.
@Test
public void count_upper_case_letters_guava() {
String catInTheHat = "The Cat in the Hat Knows a Lot About That!";
long count = CharMatcher.JAVA_LOWER_CASE.retainFrom(catInTheHat)
.length();
assertEquals(25, count);
}