This example will count the occurrences of a character in string using java, java 8, guava, apache commons and spring framework. Each snippet will use the phrase "she saw a fish on the seashore and I'm sure The fish she saw on the seashore was a saw-fish." and count the number of 'a' that exist. In a comparable illustration we demonstrate how count the number of characters in string using groovy.
Straight up Java
Using a straight up java technique we count the number of letters in specified string by iterating over each string index and checking if it equals the letter 'a'.
Java 8
Using java 8 we will count all the letters in the String first converting the string to a stream by calling String.chars(). Next we will filter the stream by passing a lambda expression that will evaluate to true if the character value equals 's'. Finally by calling a stream terminal operation we will count the total number of 's' contained in the string.
Google Guava
This snippet shows one way to count the number of times a letter occurs in a string with guava. There is an open issue to create a new method Strings.count(String string, String substring). Using guava Splitter we will split the string on the letter 'a' which will return an Iterable of elements. Then to find the count we will call Iterable.size which return 15.
Apache Commons
This snippet will counts how many times a string appears in another string with apache commons by using StringUtils.countMatches.
Spring Framework
Springframework StringUtils.countOccurrencesOf will also count the occurrences of the substring in stringToSearch.