Parallel : Groovy and Java Streams

Posted by & filed under .

iStock_000013471133XSmallThis is something that every now and then I have to do: check whether either one or all elements of a collection meet a certain criteria. The standard code initially in Java involved a for loop and iterating through the collection explicitly and checking the condition at each step.

Then Apache Commons came on with their nice utilities to specify a collection and a predicate and removed a lot of that boiler plate. (I use Apache libraries a lot but Google’s Guava and a lot of others — Spring for instance — had similar utilities.)

However, nowadays, as I spend a lot of my time dealing with Java 8 code — which has the powerful java streams — as well as Groovy, there are much easier ways of doing this, and even more so it occurred to me that these 2 are very similar, so I thought I’d draw a quick parallel here.

Here’s how you would check in Groovy that at least one element in a collection matches your criteria (let’s consider for this example we want to check that we have at least one even number):

def lst = [1, 2, 3]
def matched = lst.any { it % 2 == 0 }

Now here’s the same in Java 8 using streams:

List<Integer> lst = Arrays.asList(1, 2, 3);
boolean matched = lst.stream().anyMatch( (it) -> { it % 2 == 0} );

And if you want to change that to check that all elements in a collection match the criteria:

def lst = [1, 2, 3]
def matched = lst.every { it % 2 == 0 }

and using Java streams:

List<Integer> lst = Arrays.asList(1, 2, 3);
boolean matched = lst.stream().allMatch( (it) -> { it % 2 == 0} );

Not sure who copied from who here but I’m glad the interface is somewhat similar 🙂

Leave a Reply

Your email address will not be published.