Count occurrences in list

Similar to sister count examples, count the number of true values and count non empty strings in array list, this example will count the number of occurrences of an element in an array list using java, java 8, guava and apache commons. The data used in the snippets below was pulled from Seussvile for educators site. A comparable shows how to count the frequency of a string or number using groovy.

Straight up Java

Using a straight up java approach, we will create a Hashmap where the key will contain the element and the Map.value will hold the number of times, or count, which the element occurred. Using an enhanced for loop, we will iterate over each element checking if it exists in the map and incrementing the count.

@Test
public void number_of_occurences_in_list_java () {

    @SuppressWarnings("serial")
    ArrayList<String> seussCountActivities = new ArrayList<String>() { {
        add("findow");
        add("Balloons");
        add("Elephants");
        add("Boom Bands");
        add("findow");
        add("Hakken-Kraks");
        add("Hakken-Kraks");
        add("Hakken-Kraks");
        add("Elephants");
    }};

    Map<String, Integer> seussCount = new HashMap<String,Integer>();
    for(String t: seussCountActivities) {
       Integer i = seussCount.get(t);
       if (i ==  null) {
           i = 0;
       }
       seussCount.put(t, i + 1);
    }

    logger.info(seussCount);

    int numberOfElephants = seussCount.get("Elephants");
    assertEquals(2, numberOfElephants);
}

Output

{Boom Bands=1, Hakken-Kraks=3, findow=2, Elephants=2, Balloons=1}

Java 8

Using a java 8 we will convert the list to a stream then call Stream.filter, an intermediate operation, passing in a lambda expression to exclude all elements that don't match "Elephants". Finally calling a the reduction count method will returns the count of elements.

@Test
public void number_of_occurences_in_list_java8 () {

    List<String> seussCountActivities = Lists.newArrayList(
            "findow", "Balloons", "Elephants", "Boom Bands",
            "findow", "Hakken-Kraks", "Hakken-Kraks",
            "Hakken-Kraks", "Elephants");

    long numberOfElephants = seussCountActivities
            .stream()
            .filter(p -> p.equals("Elephants"))
            .count();

    logger.info(numberOfElephants);

    assertEquals(2, numberOfElephants);
}

Google Guava

A guava collection type Multiset, also known as a bag, contains a unique set of elements that can appear multiple times. The Multiset.count will return the number of occurrences of an element.

@Test
public void number_of_occurences_in_list_guava () {

    List<String> seussCountActivities = Lists.newArrayList(
            "findow", "Balloons", "Elephants", "Boom Bands",
            "findow", "Hakken-Kraks", "Hakken-Kraks",
            "Hakken-Kraks", "Elephants");

    Multiset<String> seussCount = HashMultiset.create(seussCountActivities);
    int numberOfElephants = seussCount.count("Elephants");

    logger.info(seussCount);

    assertEquals(2, numberOfElephants);
}

Output

[Boom Bands, Hakken-Kraks x 3, findow x 2, Elephants x 2, Balloons]

Apache Commons

Apache commons CollectionUtils.countMatches will count the number of occurrences in a collection that match a predicate in this case "Elephants".

@Test
public void number_of_occurence_in_list_apache_commons () {

    List<String> seussCountActivities = Lists.newArrayList(
            "findow", "Balloons", "Elephants",
            "Boom Bands", "findow", "Hakken-Kraks",
            "Hakken-Kraks", "Hakken-Kraks", "Elephants");

    int numberOfElephants = CollectionUtils.countMatches(seussCountActivities, new Predicate() {
        public boolean evaluate(Object arg0) {
            String compare = (String) arg0;
            return compare.equalsIgnoreCase("Elephants");
        }
    });

    logger.info(numberOfElephants);

    assertEquals(2, numberOfElephants);
}