A sister example of counting the number of instances of lower cases letters this example will count the number of upper case letters within a phrase using java 8 and guava.
Java 8
Using java 8 we will calculate the number of upper case letters. Starting with a String we will call chars() which will return a IntStream. From there we will filter out any upper case letters by passing a java 8 predicate Character::isUpperCase. 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 danielTigerLyrics = "It’s a beautiful day in the neighborhood, a beautiful day for a neighbor."
+ "Would you be Mine, could you be mine, would you be my neighbor.";
long count = danielTigerLyrics.chars().filter(Character::isUpperCase)
.count();
assertEquals(3, count);
}
Google Guava
This snippet will use guava to determine the total number of upper case letters in a String. You can think of CharMatcher as a set of characters so when we use CharMatcher.JAVAUPPERCASE it means any upper case letters. The retainFrom function will remove all non-matching characters or all non upper case values.
@Test
public void count_upper_case_letters_guava() {
String danielTigerLyrics = "It’s a beautiful day in the neighborhood, a beautiful day for a neighbor."
+ "Would you be Mine, could you be mine, would you be my neighbor.";
long count = CharMatcher.JAVA_UPPER_CASE.retainFrom(danielTigerLyrics)
.length();
assertEquals(3, count);
}