EC by Example: FlatCollect

Learn how to flatten a collection of collections into a single collection using the flatCollect method in Eclipse Collections.

Organize a collection of collections into a single collection

What is FlatCollect?

Creating Intervals from Integers and flattening them to a List

FlatCollecting a List (Java 8)

@Test
public void flatCollectingAListJava8()
{
MutableList<Integer> list = mList(5, 4, 3, 2, 1);
MutableList<Integer> result = list.flatCollect(Interval::oneTo);

MutableList<Integer> expected = mList(
1, 2, 3, 4, 5,
1, 2, 3, 4,
1, 2, 3,
1, 2,
1);
Assert.assertEquals(expected, result);
}

Collection Pipelines

@Test
public void flatCollectingAListOfMethodsToASetJava8()
{
MutableList<Class<?>> list = mList(
ListIterable.class,
MutableList.class,
ImmutableList.class);
MutableSet<String> result = list
.collect(Class::getMethods)
.flatCollect(Lists.fixedSize::with, mSet())
.collect(Method::getName)
.select(each -> each.toLowerCase().contains("flat"));

MutableSet<String> expected = mSet("flatCollect");
Assert.assertEquals(expected, result);
}

The method getMethods on class returns an array, so in the Function I pass to flatCollect, I convert the array to a List. If getMethods had returned a List or some other Iterable type, I could have simply used flatCollect passing Class::getMethods.

Here’s the same example using Java 10 with Local-variable Type Inference.

@Test
public void flatCollectingAListOfMethodsToASetJava10()
{
var list = mList(
ListIterable.class,
MutableList.class,
ImmutableList.class);
var resultSet = list
.collect(Class::getMethods)
.flatCollect(Lists.fixedSize::with, mSet())
.collect(Method::getName)
.select(each -> each.toLowerCase().contains("flat"));

var expected = mSet("flatCollect");
Assert.assertEquals(expected, resultSet);
}

Symmetric Sympathy Strikes Again

APIs covered in the examples

  1. mList — creates a MutableList
  2. mSet — creates a MutableSet
  3. Interval.oneTo(int) — creates an Interval starting from 1 to the specified value
  4. var — Local variable Type Inference included in Java 10 (JEP 286)

Refer to my previous blogs in the EC by Example series for examples of collect and select.

Check out this presentation to learn more about the origins, design and evolution of the Eclipse Collections API. There is also a video covering the slides that was recorded at an Eclipse Community Virtual Meet-up.

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

Java Champion. Creator of the Eclipse Collections OSS Java library (http://www.eclipse.org/collections/). Inspired by Smalltalk. Opinions are my own.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store