Aspects of Functional Programming in Java

Functional programming is a trending topic these days and a lot of Java programmers are hot for the features that modern functional programming languages might offer.

Waiting for Java 8 and native closure support is a nice thing but for now we’re going to take a look at several Java frameworks that are trying to implement typical structures from those functional languages where possible using the capabilities of the Java language to emulate elements like higher-order-functions, closures, options and others …

lambdaj

Lambdaj is a framework that calls itself a library to “manipulate collections in a pseudo-functional and statically typed way” and it indeed offers a nice API to apply conversions, filtering, sorting, grouping, indexing, extractions and aggregations on java collections.

More detailed examples and documentation for lambdaj can be found on the project’s website.

Maven Dependency

We need to add the following one dependency to our pom.xml to work with lambdaj:

Adding the library to a Project

Functions of different arity

Functionaljava offers generic classes to provide anonymous functions of different arities (from 1 to 8) – the last generic class type parameter is the return type the other parameters are mapped as function parameters.

Either Example

The Either represents a value from a computation of one of two possible types mapped to the left and right value of the Either instance.

Often the left value represents an exception or error thrown during the computation and the right one the value if no error was thrown.

In the following example in the first execution a NumberFormatException is thrown and either.isLeft() returns true in the second example, no exception is thrown and we’re able to fetch the computation result using either.right().value().

Option Example

An option encapsules the result of a computation and represents optional values. In Scala, instances of an Option are either an instance of Some or of None.

In the following example an integer is parsed from a given string .. in the first example, a NumberFormatException is thrown so option.isNone() returns true and option.isSome() returns false.

In the second example no exception is thrown and the opposite is the case – in addition we’re able to fetch the Integer using option.Some().

So what is the advantage of that? On the one hand, we don’t need to handle exceptions directly – on the other hand, to use an Option might give other programmers reading your code a hint that the performed computation might not yield a result and it is necessary to handle that.

There are many other interesting features present in this library so if you’re interested please take a look at the detailed information on the project’s website.

Guava

Guava is the modern version of commons-collections (also described in this article) and offers some helpful APIs for handling collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O and other stuff.

Optional

Guava offers a structure to signal that the result of a computation might yield no result – Optional.

In the following example the first computation throws a NumberFormatException and no result is possible – in the second call we’re able to test for valid computation and return the value from the operation. As you might have noticed this approach is similar to the Option of the functionaljava example.

Apache Commons Collection

Though commons collections has no support for generics it is still used or referenced in many projects. There are three features that I’d like to demonstrate here:

Closures: Are simple functions that allows us to get a reference to each object in the collection and alter the object

Transformers: Enables us to transform data from one format into another

Predicates: Similar to the Guava example above the allow us to test each element of a collection to filter a collection

If you’re used to commons collections that much that you do not want to switch to Guava for some of the features please take a look at the collections-generics project on GitHub – it’s an implementation of commons-collections with generics support.

Maven Dependencies

We just need one dependency to integrate commons-collections into our project..

Predicates to filter Collections

The following example filters a list of books by their title so that all books with a title that does not contain the string book are filtered from the collection. As you might have noticed – in contrast to Guava without generics we’re forced to work with an object in our predicate.

Closures

We’re recycling the book list from the example above and we’re applying a closure to each element of the collection that print’s the books title:

Closure closure =new Closure(){publicvoid execute(finalObject obj){Book book =(Book) obj;System.out.println("the book's title is: "+ book.getTitle());}};
CollectionUtils.forAllDo(books, closure);// the book's title is: Some book// the book's title is: Another book// the book's title is: I luv codin

Transformer

First of all we’re recycling the list of books and the title-printing-closure from the examples above – second we’re applying a transformer on the collection of books to create a new collection of books with a modified title..

Funcito

Funcito is a shiny new library that simplifies access to our favourite functional java libraries like functionaljava, guava or jedi – and allows us to use the structures of these frameworks with less writing

The following libraries and features are currently supported:

Google Guava Function and Predicate interfaces

Functional Java the F (function) interface

Jedi-core Functor and Filter interfaces

Play! Framework 2 F.Function interface

Collection-generic Transformer and Predicate interfaces

I’ll be covering only a few examples here but if you’re interested, please take a deeper look at the Funcito project website.

I have just released an update to Funcito as version 1.3.0, which adds support for an additional functional API (the Netflix RxJava framework), as well as a cool new feature called “modes — including a Safe Navigation mode (like the Groovy safe navigation operator) to handle nulls while chaining method calls. http://funcito.googlecode.com