Frequency of object in collection

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.

String randomParagraph = "Difficulty on insensible reasonable in. From as went "
        + "he they. Preference themselves me as thoroughly partiality considered "
        + "on in estimating. Middletons acceptance discovered projecting so is so "
        + "or. In or attachment inquietude remarkably comparison at an. Is "
        + "surrounded prosperous stimulated am me discretion expression. But "
        + "truth being state can she china widow. Occasional preference fat "
        + "remarkably now projecting uncommonly dissimilar. Sentiments projection "
        + "particular companions interested do at my delightful. Listening newspaper "
        + "in advantage frankness to concluded unwilling.";

List<String> words;

public void setUp () {

    words = Splitter.on(CharMatcher.anyOf(" ."))

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.

public void frequency_of_object_in_collection_java () {

    int numberOfOccurences = Collections.frequency(words, "me");

    assertEquals(2, numberOfOccurences);

Java 8

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.

public void frequency_of_object_in_collection_java8_lambda () {

    long numberOfOccurences = words
            .filter(p -> p.equalsIgnoreCase("me"))

    assertEquals(2, numberOfOccurences);

Google Guava

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".

public void frequency_of_object_in_collection_guava () {

    int numberOfOccurences = Iterables.frequency(words, "me");

    assertEquals(2, numberOfOccurences);

Apache Commons

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.

public void frequency_of_object_in_collection_apache () {

    int numberOfOccurences = CollectionUtils.cardinality("me", words);

    assertEquals(2, numberOfOccurences);