Groovier Groovy with Java 8 Streams

Image for post
Image for post

Consider writing Groovy code to retrieve the transformed version of an element from a given collection such that transformed version of the element satisfies a given predicate.

Here’s a Groovy-only code snippet that uses only the features of Groovy.

Here’s a Groovy+Java code snippet that uses Java 8 streams.

While the first snippet transforms (collect) every element in the source collection before executing findResult (staged execution), the second snippet executes the entire pipeline of functions for every element in the source collection. Consequently, the Groovy+Java snippet is more efficient as it stops transforming the elements as soon as the transformed version of an element is found.

In terms of parallelism, here’s the Groovy-only snippet parallelized using GPars.

While collect is parallelized (as collectParallel), findResult isn’t parallelized as it isn’t supported by GPars. Further, even if findResult was parallelized, it will only execute after collectParallel completes and, hence, the above observed inefficiency due to the staged execution will still persist.

In comparison, here’s the parallelized version of the Groovy+Java snippet.

Unlike the parallelized Groovy-only snippet, each function in the pipeline is executed in parallel as its input becomes available. Hence, this will be more efficient than the parallelized Groovy-only snippet.

Few years ago, Groovy made Java groovier. With Java 8 streams, I think Java can make Groovy groovier.

That said, I am eager to see how will Groovy evolve to make Java groovier.

Written by

Programming, experimenting, writing | Past: SWE, Researcher, Professor | Present: SWE

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