EC by Example: CountBy

Learn how to use the countBy method in Eclipse Collections.

Count the fruit by color

CountBy

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.

RED is the top fruit color

Here’s the code in plain text if you would like experiment on your own.

public enum Fruit
{
APPLE(Color.RED),
BANANA(Color.YELLOW),
CHERRY(Color.RED),
PEAR(Color.GREEN),
STRAWBERRY(Color.RED),
LEMON(Color.YELLOW),
KIWI(Color.GREEN);
    private final Color color;
    private static final ImmutableBag<Color> 
COUNTS_BY_COLOR =
Bags.immutable.with(Fruit.values())
.countBy(Fruit::getColor);
    Fruit(Color color)
{
this.color = color;
}
    public Color getColor()
{
return this.color;
}
    public static int getColorCount(Color color)
{
return COUNTS_BY_COLOR.occurrencesOf(color);
}
    public static boolean isTopColor(Color color)
{
return COUNTS_BY_COLOR.topOccurrences(1)
.anySatisfy(each -> each.getOne() == color);
}
    public enum Color
{
RED, YELLOW, GREEN
}
}

And the code for the test.

public class FruitTest
{
@Test
public void redFruit()
{
Assert.assertEquals(3,
Fruit.getColorCount(Fruit.Color.RED));
Assert.assertTrue(
Fruit.isTopColor(Fruit.Color.RED));
}
    @Test
public void yellowFruit()
{
Assert.assertEquals(2,
Fruit.getColorCount(Fruit.Color.YELLOW));
Assert.assertFalse(
Fruit.isTopColor(Fruit.Color.YELLOW));
}
    @Test
public void greenFruit()
{
Assert.assertEquals(2,
Fruit.getColorCount(Fruit.Color.GREEN));
Assert.assertFalse(
Fruit.isTopColor(Fruit.Color.GREEN));
}
}

APIs covered in the examples

  1. countBy — Counts the elements Collection by the Function specified and returns a Bag.
  2. Bags.immutable.with — Creates an ImmutableBag with the specified vararg’d elements. There are mutable and immutable Collection factories in Eclipse Collections.
  3. occurrencesOf — Returns the count from a Bag for a particular item.
  4. 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.

Eclipse Collections is open for contributions. If you like the library, you can let us know by starring it on GitHub.