Count booleans in list

Similar to sister count examples, count the number of occurrences and count non empty strings in array list, this example will count the number of values in a collection that are true using java, java 8, guava and apache commons. In a related example we demonstrate counting boolean values elements in array using groovy.

Straight up Java

Using straight up java we will count the number of booleans in a list by using an enhanced for each looping over the collection while maintaining a count of the number of elements that equal true.

@Test
public void count_booleans_arraylist_java () {

    List<Boolean> values = Lists.newArrayList(true, true, false, true, false);

    int count = 0;
    for (Boolean value : values) {
        if (value.booleanValue()) {
            count ++;
        }
    }

    assertEquals(3, count);
}

Java 8

Java 8 introduced reduction operations which return one value by combing the contents of a stream. Below, we will use a lambda expression to filter elements that equal to true then call the Stream.count to count the number of booleans that exist in the stream.

@Test
public void count_booleans_arraylist_java8 () {

    List<Boolean> values = Lists.newArrayList(true, true, false, true, false);

    long count = values.stream().filter(p -> p == true).count();

    assertEquals(3, count);
}

Google Guava

Using guava Booleans utility class we will call Booleans.countTrue which accepts an array and returns the number of the values equaling true.

@Test
public void count_booleans_arraylist_guava () {

    List<Boolean> values = Lists.newArrayList(true, true, false, true, false);

    int count = Booleans.countTrue(Booleans.toArray(values));

    assertEquals(3, count);
}

Apache Commons

Apache commons CollectionUtils.countMatches will count the number of elements that match the provided predicate, in this case that will evaluate to true.

@Test
public void count_booleans_arraylist_apachecommons () {

    List<Boolean> values = Lists.newArrayList(true, true, false, true, false);

    int count = CollectionUtils.countMatches(values, new Predicate() {
        @Override
        public boolean evaluate(Object object) {
            Boolean val = (Boolean) object;
            return val.booleanValue();
        }
    });

    assertEquals(3, count);
}