EC by Example: CountBy
Learn how to use the countBy method in Eclipse Collections.
The method countBy returns a Bag in Eclipse Collections. A Bag is an unordered Collection which allows duplicates. The internal structure of the HashBag implementation in Eclipse Collections is an ObjectIntHashMap. The keys of the internal map are the items, and the values are the counts stored as ints. The method countBy takes a Function as an argument.
The following code will illustrate how to count a collection of Fruit by their color, using a method reference. We store the result in a variable named COUNTS_BY_COLOR.
We have two methods that query the ImmutableBag that is created. They are used in the following tests.
Here’s the code in plain text if you would like experiment on your own.
public enum Fruit
private final Color color;
private static final ImmutableBag<Color>
this.color = color;
public Color getColor()
public static int getColorCount(Color color)
public static boolean isTopColor(Color color)
.anySatisfy(each -> each.getOne() == color);
public enum Color
RED, YELLOW, GREEN
And the code for the test.
public class FruitTest
public void redFruit()
public void yellowFruit()
public void greenFruit()
APIs covered in the examples
- countBy — Counts the elements Collection by the Function specified and returns a Bag.
- Bags.immutable.with — Creates an ImmutableBag with the specified vararg’d elements. There are mutable and immutable Collection factories in Eclipse Collections.
- occurrencesOf — Returns the count from a Bag for a particular item.
- topOccurrences — Returns a List of items and their counts in descending order by the number of occurrences.
Check out this presentation to learn more about the origins, design and evolution of the Eclipse Collections API.