EC by Example: GroupBy

Learn how to group elements of a collection using Eclipse Collections.

Happy New Year!

This is my first blog in 2019. I will keep it brief. Time for some code.

Group By

The method groupBy returns a Multimap in Eclipse Collections. A Multimap looks like a Map in that it has methods like get and put, but the values in a Multimap are always some Collection type, like a List, Set or a Bag.

The following code will illustrate how to group a collection of Fruit by their color. We store the result of the grouping in a variable named FRUIT_BY_COLOR. Notice that the type is a specific kind of Multimap, because we called groupBy on an ImmutableBag.

Fruit as an Enum with Color as an inner Enum

The we can query the FRUIT_BY_COLOR Multimap for each color using the getFruitByColor method on the Fruit enum.

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 ImmutableBagMultimap<Color, Fruit>
FRUIT_BY_COLOR =
Bags.immutable.with(Fruit.values())
.groupBy(Fruit::getColor);

Fruit(Color color)
{
this.color = color;
}

public Color getColor()
{
return this.color;
}

public static ImmutableBag<Fruit> getFruitByColor(Color color)
{
return FRUIT_BY_COLOR.get(color);
}

public enum Color
{
RED, YELLOW, GREEN
}
}

And the code for the test.

public class FruitTest
{
@Test
public void redFruit()
{
Assert.assertEquals(
Bags.immutable.with(
Fruit.APPLE,
Fruit.CHERRY,
Fruit.STRAWBERRY),
Fruit.getFruitByColor(Fruit.Color.RED));
}

@Test
public void yellowFruit()
{
Assert.assertEquals(
Bags.immutable.with(
Fruit.BANANA,
Fruit.LEMON),
Fruit.getFruitByColor(Fruit.Color.YELLOW));
}

@Test
public void greenFruit()
{
Assert.assertEquals(
Bags.immutable.with(
Fruit.PEAR,
Fruit.KIWI),
Fruit.getFruitByColor(Fruit.Color.GREEN));
}
}

APIs covered in the examples

  1. groupBy — Groups a Collection into a Multimap using the specified function to calculate a key for each object. The type of Collection determines the type of Multimap that is returns.
  2. Bags.immutable.with — Creates an ImmutableBag with the specified vararg’d elements. There are mutable and immutable Collection factories in Eclipse Collections.
  3. get — Returns a Collection from a Multimap. In the case of an ImmutableBagMultimap returns an ImmutableBag.

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.