This example will count the occurrences of a word within a paragraph. It should locate the number of elements in the collection that are equal to the specified object.
In the setup method, we will use Guava's Splitter to split the paragraph to a list.
Straight up Java
Java Collections utility class contains a method named frequency. As it sounds, it will find the number of elements in a specified collection that equals to the parameter passed. For our example, we will pass in the list of words and ask how many times does the word "me" appear in the array list.
This snippet will demonstrate how to count the number of times an object appears in an arraylist using java 8. The Streams API provides a terminal operation which will count the number of elements in a stream. Passing a predicate to the filter method that will return true if the string equals "me" we then will call Stream.count to determine the total number of times "me" appears in the stream.
The snippet below will find the number of occurrences of an object in a collection using guava. Iterables.frequency counts the number of elements in an iterable that equal a specified object or in this case "me".
A cardinality is the number of elements in list that match a given property. Using apache commons CollectionUtils.cardinality will determine the number of times "me" appears in the arraylist words.