Benji's Blog

Tuples in Java

The absence of tuples in Java is often bemoaned. Tuples are collections of a variety of types. They might look like (“benji”,8,”weber”) – a 3-tuple of a string, a number, and another string. People often wish to use tuples to return more than one value from a method.

Often this is a smell that we need to create a domain type that is more meaningful than a tuple, but in some cases tuples are actually the best tool for the job.

We can pretty easily create our own tuple types, and now that we have Lambdas we can consume them pretty easily as well. There is a little unnecessary verbosity left over from type signatures, but we can avoid it in most cases.

If we want to return a tuple from a method, by statically importing an “tuple” method that is overloaded for each arity of tuple we can do

static TriTuple me() {
    return tuple("benji",9001,"weber");
}

Other than the return type of the method it is fairly concise.

On the consuming side it would be nice to be able to use helpful names for each field in the tuple, rather than the ._1() or .one() accessors that are used in many tuple implementations.

This is easily realised thanks to lambdas. We can simply define a map method on the tuple that accepts a function with the same arity of the tuple, to transform the tuple into something else.

Using the above method now becomes

String name = me()
    .map((firstname, favouriteNo, surname) -> firstname + " " + surname);

assertEquals("benji weber", name);

We can even throw checked exceptions on the consuming side if we allow our map method to accept functions that throw exceptions.

String name = me()
    .map((firstname, favouriteNo, surname) -> {
        if (favouriteNo > 9000) throw new NumberTooBigException();
        return firstname;
    });

Of course we’d also like identical tuples to be equal to each other so that this is true.

assertEquals(tuple("hello","world"), tuple("hello", "world"));

The implementation looks like this, re-using the value-object pattern I described previously

public interface Tuple {
    //...
    static  TriTuple tuple(A a, B b, C c) {
        return TriTuple.of(a, b, c);
    }
    //...
}

public interface TriTuple {
    A one();
    B two();
    C three();
    static  TriTuple of(A a, B b, C c) {
        abstract class TriTupleValue extends Value> implements TriTuple {}
        return new TriTupleValue() {
            public A one() { return a; }
            public B two() { return b; }
            public C three() { return c; }
        }.using(TriTuple::one, TriTuple::two, TriTuple::three);
    }

    default  R map(ExceptionalTriFunction f) throws E {
        return f.apply(one(),two(),three());
    }

    default  void consume(ExceptionalTriConsumer consumer) throws E {
        consumer.accept(one(), two(), three());
    }
}

Browse the full code on Github