EC by Example: Filtering

Learn how to filter a collection using Eclipse Collections.

Image for post
Image for post

Filtering: Include or Exclude?

If you have a single method named filter, how do you know if it is supposed to be an inclusive or exclusive filter? In Eclipse Collections, there are two filtering methods named select and reject.

Image for post
Image for post

Filtering an Object List

public void filteringUsingSelectAndReject()
MutableList<Integer> mList = mList(1, 2, 3, 4, 5);
ImmutableList<Integer> iList = iList(1, 2, 3, 4, 5);

Predicate<Integer> evens = i -> i % 2 == 0;

Filtering a primitive List

public void filteringPrimitivesUsingSelectAndReject()
MutableIntList mList = IntLists.mutable.with(1, 2, 3, 4, 5);
ImmutableIntList iList = IntLists.immutable.with(1, 2, 3, 4, 5);

What other types support Select and Reject?

The Symmetric Sympathy is strong with select and reject.

Image for post
Image for post
Select and Reject is available across many types and concerns

Possible to filter both inclusively and exclusively in one iteration?

Yes. There is a method called partition. I will show partition in the next blog in this series.

APIs covered in the examples

  1. Select (Eager, Lazy and Parallel) — filters including elements that match a condition
  2. Reject (Eager, Lazy and Parallel) — filters excluding elements that match a condition
  3. mList — Creates a MutableList
  4. iList — Creates an ImmutableList
  5. IntLists.mutable.with — Creates a MutableIntList
  6. IntLists.immutable.with — Creates an ImmutableIntList
  7. asLazy — Returns a LazyIterable or LazyIntIterable
  8. asParallel — Returns a ParallelIterable
  9. toList — Converts the target Iterable into a MutableList

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

Written by

Java Champion. Creator of the Eclipse Collections OSS Java library ( 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