Category Archives: Dev notes

My first Java 8 Lambda applied while using Drools

In one of the projects I’m working on, a Java EE and web application using Drools, data is shard-ed (splitted) across many knowledge sessions having their own knowledge base definitions – for different business reasons not described in this post. From an end-user perspective it is sometime required to perform the “union” of the results coming from a given Drools’ query, which may be defined in several, but not necessarily all, of the knowledge sessions.

Technically the query can be identified by a specific name and I need to “pull” the query results from each of the several knowledge sessions which actually have such query defined, finally merging all results into a single response.

In order to determine if a given knowledge session, do actually contain the query or not, I came up with:

boolean containsQuery = kieSession.getKieBase().getKiePackages().stream()
		.anyMatch(p -> p.getQueries().stream()
			.anyMatch(q -> q.getName().equals( queryName )));

Why I like it

Before Java 8 I had to use external iteration, and this was a little bit tedious especially for optimization purposes as explicitly iterating through Packages and Query names, I needed to manually manage to break out of /exit the iterations once the query was actually found.

Now that Java 8 is here with Lambda and Streams, and now that I can use it also on this codebase, writing code to perform this kind of operation is more trivial, and it’s also quite more of a “fluent” code to read in my opinion.

Why I like Java 8 Lambdas, and Streams

Because I like Functional Programming concepts, and as above I can switch from an external iteration to an internal iteration, where not only I don’t have any longer to manually manage Iterators, but also I could expect optimizations to “automagically” pop-up sometimes (e.g.: the code above should early terminate with true, if a true is returned by any of the lambdas at some point), but also I can finally pass a Function (Lambda) instead of every time declaring anonymous classes!

Advertisements