Archive for February, 2007

Java Closure Examples

One thing I miss in the current BGGA proposal for closures in Java 7, is a good set of examples. There are some examples, but they don’t cover most situations. Also I feel that more examples might better show the advantages of having closures in Java. Of course, as long as the Java compiler has not been patched to work with closures, this remains “swimming on dry land” (as we say in Holland). Syntax errors will no doubt be abundant, and everything might change with the next version of the proposal. I hope this will still be useful to people wondering why there should be closures in Java in the first place. This is why: it makes your code cleaner and leaner.

So here goes, starting with some simple examples. Each example consists of the closure method usage (which will probably be used most) and the closure method definition (which will mostly be done by library developers).

Select objects from collection

This is an example of how the CollectionUtils utility methods could be rewritten using closures.

public Collection<Book> getPublishedBooks(Collection<Book> books) {
    return select(books, {Book book =>
        book.isPublished()
    });
}

/**
 * Returns the T objects from the source collection for which the
 * given predicate returns true.
 *
 * @param source
 *            a collection of T objects, not null
 * @param predicate
 *            returns true for a given T object that should be
 *            included in the result collection
 * @return a collection of T objects for which the predicate
 *         returns true
 */
public static <T> Collection<T> select(Collection<T> source,
        {T=>Boolean} predicate) {
    Collection<T> result = new ArrayList<T>();
    for (T o : source) {
        if (predicate.invoke(o)) {
            result.add(o);
        }
    }
    return result;
}

Continue Reading »

2007-02-05. 17 responses.