EC by Example: InjectInto

Learn one of the most general, flexible, and least understood iteration patterns in Eclipse Collections.

Image for post
Image for post
Grounds for Sculpture, Hamilton N.J.

Continuum Transfunctioner

Like the Continuum Transfunctioner from “Dude, Where’s my car”, the method injectInto is a very mysterious and powerful method, and its mystery is only exceeded by its power.

So what does injectInto do?

The method injectInto can be used to do pretty much anything. The method injects an initial value into a two argument function along with the first element of the collection, and calculates some result. That result is then passed to the next invocation of the function as the initial value along with the next element of the collection. And so on and so forth until all elements of the collection have been visited and a final result is returned.

The name injectInto is based on the inject:into: selector from Smalltalk. InjectInto is an alternative name for foldLeft or reduce.

I will illustrate ways to implement various algorithms using injectInto to show how mysterious and powerful it is.

Example: Min and Max

Example: Sum

Example: Product

Example: Collect

Example: GroupBy

Example: Collectors.groupingBy

Example: Detect

Example: Select

APIs covered in the examples

  1. injectInto — applies a two argument function to each element of a collection using an initial value, and then injecting the result of each application of the function into the next iteration.

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.

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