Pages

Thursday, November 10, 2011

Introduction to LambdaJ: Get rid of those pesky loops

After a very long pause, I thought it'd be nice to introduce some cool Java technologies I stumbled upon lately.

So, straight to business, I want to talk a bit about LambdaJ. It's a super cool infrastructure which is targeting those loops you always end up writing in Java.

Let's see some examples.
Say you've got an address book, and it's saved in a List<Person> where Person has a getSurname() method.
We wish to get all those Smiths among the members of the address book.
Now, usually you find yourself writing something like:
List<Person> smiths = new ArrayList<person>();
for (Person person : addressBook) {
    if (person.getSurname().equals("Smith")) {
        smiths.add(person);
    }
}

Instead, we like this clean Python syntax:
smiths = [person for person in addressBook if person.getSurname() == "Smith"]

So, Java is not the most flexible language there is, but this LambdaJ syntax really nears perfection.
This will look like:
List<Person> smiths = select(addressBook, having(on(Person.class).getSurname().equals("Smith")));

Ok, that was nice. Now let's look at a foreach block.
Regularly, we'd see something like:
for (Person knight : newKnights) {
    knight.setTitle("Sir");
}

We could do this instead:
forEach(newKnights).setTitle("Sir");

Finally, lets sort. I won't even write the code that sorts the address book by first name without LambdaJ.
With LambdaJ it looks really cool:
sort(addressBook, on(Person.class).getFirstName());

So, many thanks to the developers who wrote this project, and for making it open source.
That's all for now, thanks for reading.

No comments:

Post a Comment