Guava collections and functional approach
By the time I had my first encounter with guava library, I expected it to be just as similar as apache’s commons. which I extensively used before. But soon I realised it was almost nothing similar. One of the things I liked a lot was the idea of using functions as input parameter 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 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 realise 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 filter takes a Predicate as an argument. Of course the release of Java 8 and it’s 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 towards the design and implementation of the approach.