EC by Example: Counting
Learn how to count the elements of a collection that match a Predicate using Eclipse Collections.
How do you count using Eclipse Collections?
The method count takes a Predicate as a parameter and returns the number of the elements in a collection that match.
There is also a countWith method which takes a Predicate2 and a countBy method which takes a Function.
Counting elements of a Collection
Here’s a simple enum we’ll use to identify different things in a Collection.
public enum SkyEntity
HELICOPTER(true), SKYSCRAPER(false), BIRD(true);
this.flies = flies;
private boolean flies;
public boolean canFly()
Now, let’s count some things. First, I will create a MutableBag of SkyEntity instances using addOccurrences to set the counts directly. Then I will convert the MutableBag to a MutableList. Then I will use count to count the number of HELICOPTER and countWith to count the number of SKYSCRAPER.
public void count()
MutableBag<SkyEntity> bag = Bags.mutable.empty();
MutableList<SkyEntity> list = bag.toList();
Bag<Boolean> flies = list.countBy(SkyEntity::canFly);
Finally, I group and count the SkyEntity who can and can’t fly using countBy with a Function which returns a Boolean.
Counting Primitive Collections
Eclipse Collections has a full complement of primitive collections. Each primitive collections supports a count API. Here are a couple examples of counting with primitive collections.
public void countPrimitive()
IntList intList = IntInterval.oneTo(10);
Assert.assertEquals(3, intList.count(i -> i % 3 == 0));
CharAdapter chars =
"the quick brown fox jumps over the lazy dog");
Assert.assertEquals(2, chars.count(c -> c == 't'));
APIs covered in the examples
- count / countWith — counts the number of elements of a collection that match a given Predicate or Predicate2.
- countBy — counts elements of a collection grouping them by some Function.
- Bags.mutable.empty — creates an empty MutableBag.
- occurrencesOf — counts the number of occurrences of an item in a Bag.
- toList — converts a collection to a MutableList.
- IntInterval.oneTo — creates an IntInterval which is an ImmutableIntList from one to the specified number.
- IntPredicates.isEven / isOdd — creates an IntPredicate which tests if an int is even or odd.
- Strings.asChars — creates a CharAdapter wrapping the specified String.
Check out this presentation to learn more about the origins, design and evolution of the Eclipse Collections API.