“For” hack with Option monad in Java

There has been some discussion going on in the blogosphere about monads, and especially about the Haskell Maybe monad or the Scala option class. Those are ways to prevent problems with NULL and NPEs that Java lacks. Java returns NULL form many methods to indicate failure or no result. Suppose we have a method which returns a name:

String name = getName("hello");
int length = name.length();

The problem with this method is that we don't know if it returns null. So the developers needs to deal with length == null, though the compiler doesn't force the developer to deal with the returned NULL. A lazy developer then leads to null pointer exceptions. Other languages deal in different ways with this problem. Groovy has safe operators and Nice has option types.

Some posts like the one from James show how to use options in Java. All have the problem that you need to unwrap the value inside the option / maybe. Scala ans Haskell do that automatically for you, with the case classes in Scala for example.

But there is a construct with syntactic sugar in Java which unwraps the value from inside another class: the for loop from Java 1.5.

Option[String] option = getName("hello");

for (String name: option) {
	// do something with name

To make this work we need our option class to implement Iterable.

public abstract class Option[T] implements Iterable[T] {

And the None and Some sub classes to return an empty iterator

public abstract class None[T] extends Option[T] {
  public Itertator[T] iterator() { return EMPTY_ITERATOR; }

or an iterator with one item.

public abstract class Some[T] extends Option[T] {
  public Itertator[T] iterator() { 
    // or better use google-collections
    List[T] list = new ArrayList[T]();
    return list.iterator();

Then voila Java does the unwrapping for us and instead of

Option[String] option = getName("hello");
if (option instance of Some) {
    String name = ((Some) option).value();
} else { ... }

we can write (sacrificing the else):

for (String name: getName("hello")) {
	// do something with name

Thanks for listening.

Update: Completely ignoring the point of this post, Euxx posted a correction for the single element list creation I did.

  return Collections.singletonList(this.value).iterator();

Happens all the time in IT, people missing the point but nitpicking on something irrelevant. Other than that, if we start arguing performance, "The java.util.Collections class also have number of other utility methods that allow to shorten code like this and help to improve performance of your application." I'd write (or reuse) a OneElementIterator something like this (could probably be optimized with some further thinking)

public class OneElementIterator[T] implements Iterator[T] {

	private boolean done = false;
	private T element;
	public OneElementIterator(T element) {
		this.element = element;
	public boolean hasNext() {
		return ! done;
	public T next() {
		done = true;
		return element;
	public void remove() {
		// not supported, throw exception;

(Or again using google collections)

"I can't not notice the ugly use of ArrayList to create collection with a single element, but what made matter worse, is that author suggested to use 3rd party library to replace those 3 lines of code."

As far as I know, the JDK does not help you very much with Iterators or Iterables as third party libraries do. So, yes, I'd suggest using a third party library to implement an Iterator/Iterable for Option.

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