Towards A More “Functional” Java (The Sweet Nectar of Guava)
Recently, on a client project, our development team completed a significant refactoring of a fairly large Java EE web application. Since this required updating many disparate parts of our codebase, some of which I was not as familiar with, it also served as an informal code review.
Once underway, I started noticing a fairly common pattern emerging - one that I have seen in many other applications. It goes like this: Given an existing collection of homogeneous objects, we wish to find the ones that match specific criteria(s). In other words, we wish to filter the collection.
Consider a trivial example, where, given a list of integers, we want to find all of the even numbers. Here is a naive Java implementation:
This could probably be optimized some more, but you get the idea.
If you are familiar with functional languages, you will recognize what we are doing is akin to a filter or select. For example, it’s very simple to achieve the identical functionality in Ruby:
But we know that Java lacks the syntactic sugar to be able to express this as simply as we can in Ruby and other functional languages. However, we can get part of the way there using the Guava project from Google. It greatly enhances the existing Collections API and adds some pseudo-functional features.
Here is another Java implementation, this time using some features from the Guava library.
Admittedly, this is overkill for such a trivial example. Also, it’s not immediately obvious what the Predicate interface and the apply() method we are implementing are actually doing. However, the power will start to shine through once we have more complex business logic and filter criteria.
Think about searching for a pair of new shoes from an online store. Almost all of today’s websites offer some sort of filter functionality to narrow down your results to display only those that match a particular criteria. This could be brand, availability, size, color, etc.
The following example demonstrates how we could filter a list of results to only return items that qualify for free shipping. For the sake of this example, an item qualifies for free shipping if it’s price is equal to or greater than $25 and it is available in inventory.
There is something in the light that I see.
