Thursday, February 3, 2011

Less (looping) noise with lambdaj

 I know a Java developer who became a project manager when he couldn't stand the pain of having to write yet another loop ;)

If you're stuck with Java and can't use Groovy or less noisy languages, how about doing more with less?

Lambdaj to the rescue! Lambdaj is a powerful library that allow us to manipulate collections in a psudo-functional and statically-typed way. Just a a couple of examples:

Let's say that a collection of task objects and I want to collect the id for each of them.

With your regular Java loop you'd probably write:

With lambdaj I'd write:

OK, that was just one line!

Let's say I want to filter the roles equal to "admin"

The iterative version:

And with lambdaj:

And there's more. Another common task while working with collections is to aggregate their items in some way. Let's say that we have a list of tasks objects with end dates and I want to get the max end date for all of them.

Without lambdaj's aggregating functions:

With lambdaj you just write:

This is just a small taste. See more features here:

Download and loop less!


  1. i don't get how would one prefer to use "List prodPlanIds = collect(productionPlans, on(ProductionPlan.class).getId());" over "productionPlans*.id/getId()" :)

  2. The on method is used throughout lambdaj in order to statically define a method that needs to be invoked on given class of objects. I love Groovy and but sometimes it's not a matter of which one you prefer ;)