Guava collections and functional approach

Hafiz Hasanov
2 min readMar 19, 2015

By the time I had my first encounter with the guava library, I expected it to be just as similar to apache’s commons. which I extensively used before. But soon I realized it was almost nothing similar. One of the things I liked a lot was the idea of using functions as input parameters for such methods as filtering or transforming iterables. I didn’t struggle to grasp the idea, because I had the basic knowledge of functional programming with Haskell and also a tiny bit of experience with JavaScript. Yet, being a recent graduate I didn’t dot have much experience with beautiful oop design. I was curious to see how it was implemented. Turned out to be a simple idea, to define a Function object. Genius. Now I think about it and feel ashamed to realize that I could have never thought of such a simple idea.

Back to guava, the usage is pretty straightforward.

Iterable circles = Iterables.transform(rectangles, new Function(){ 
@Override
public CircularShape apply(RectangularShape input) {
return new CircularShape(input.getId(), input.getHeight(), input.getWidth());
}
});

Apart from Function, some functions such as filters take a Predicate as an argument. Of course, the release of Java 8 and its support for lambda expressions removes the need to use these functions. This part of guava addresses users before Java 8, which is quite new and not actively used by many people. In any case, as it is also stated in guava wikis, it is not always of the best readability to use this approach over imperative code[1]. So this post is more of a result of my desire to share my curiosity about the design and implementation of the approach.

--

--