Creating a fluent interface for Google Collections

Chris wrote about functional programming in Java. As an example he used Google Collections which "is a suite of new collections and collection-related goodness for Java 5.0".

Looking at his post he gives the following code on how to use Goolge Collections

files = Iterables.transform(
  new PagesToFilesTransformation()))

This is very verbose and hard to read. Mostly due to the static method calls and the seperation of the first "filter" and the "new PagesToFilesTransformation()" parameter. Using a static import we can reduce this to:

import static Iterables.*;

      filter(getPagesList(),WebPage.class), undeletedPages), 
   new PagesToFilesTransformation()))

Better. I'll show you how to make this even more readable with a fluent interface. I use the following example for this:

List names = Arrays.asList("Stephan", "Chris", "Mike", "Miha", "Katrin");

Iterable filtered =  Iterables.filter(
  Iterables.filter(names, or( isEqualTo("Katrin"), isEqualTo("Miha"))),
    lengthLessThan(5)) ;

We want to move this code to a fluent interface. Martin Fowler wrote about Fluent Interfaces on his bliki and there is a entry on Wikipedia. They were made popular by JMock as a way to specify mock expectations.


What is a fluent interface though? For me it's an interface to an API which is more consistent and readable. Which helps you do several steps with an API in a correct way. It's often implemented with speaking method names and call chaining. These together create the illusion of natural, descriptive language. When the chained methods return the correct type, most often it's impossible to call the wrong methods or methods in the wrong sequence. Therefor fluent interfaces create better readable code with less bugs. Which distinguishes them from domain specific languages (like in Ruby on Rails), macro programming (Lisp) or plain language constructs (methods which take closures) like "[1..5].each { ... }". The differences is fluent 😉 "5.times.each {...}" could be considered a simple fluent interface.

The most recent fluent interface in Java with some fame is Quaere, a kind of LINQ for Java for querying object graphs. There even is a promising Quaere API for JPA. I really think fluent interfaces are useful, although others think they are stupid. I keep to myself what I think is stupid and we see where this all is going to.

Back to our example. I've recently shown how to create a fluent interface for object creation. One for Google Collections might look like this:

Iterable<T> filtered = 
   .filter( or(isEqualTo("Chris"), isEqualTo("Miha")))

This example isn't optimal, but much more readable than the one given by Chris. The or() part could be improved because it doesn't look very nice. This will change with closures. Fluent interfaces will boom with closures in Java 7.

In the comment to his blog post, Chris mentions "Making a fluent interface to do this might be a little risky, because I think there’s an expectation* that a method like Iterable.filter() wouldn’t modify the source iterable itself, but rather would return a new, filtered iterable." We do not need to modify the Iterable, we only hold a reference and create new fluent interfaces on the fly as needed. Our code to enable a fluent interface for Google Collections this is rather simple:

public class FluentIterable<T> implements Iterable<T> {
  private Iterable<T> iterable;

  public FluentIterable(Iterable<T> iterable) {
    this.iterable = iterable;

  public static <T> FluentIterable<T> with(Iterable<T> iterable) {
    return new FluentIterable<T>(iterable);

  public FluentIterable<T> filter(Predicate<? super T> predicate) {
    return new FluentIterable<T>(
        Iterables.filter(this.iterable, predicate)

  public Iterator<T> iterator() {
    return this.iterable.iterator();

This example has several main points. The with() static method call is descriptive and creates a fluent interface object for us to hold the Iterable object. Second most methods in fluent interfaces return the object itself. We create a new fluent interface object in filter to wrap the filtered iterable and enable chaining. My last example with object creation did hold the same bean and did not create new objects on the fly. This really depends on what should be done. We could have set the new iterable instead of creating a new wrapper like this:

  public FluentIterable<T> filter(Predicate predicate) {
    Iterable filtered = Iterables.filter(this.iterable, predicate);
    this.iterable = filtered;
    return this;

This mostly depends on your style and if you think immutable objects are good or bad. For this I prefer the immutable Fluent Interface object over the mutable. Perhaps this is a pattern.

Conculsion:: A fluent interface for Google Collections would be useful. It's more readable, less error prone and flows. Although my example works and is usable, there needs to go more work into a fluent interface for Google Collections to make it useful. For example support more Predicates and support transformations.

Thanks for listening.

Stephan Schmidt Administrator
CTO Coach , svese
Stephan is a CTO coach. He has been a coder since the early 80s, has founded several startups and worked in small and large companies as CTO. After he sold his latest startup he took up CTO coaching. He can be found on LinkedIn or follow him in Twitter.
follow me