A Java tuple class (Tuple2 or Pair, if you prefer)

After working with Scala for a long time, I had to come back to Java for a while to work on an Android app. Right away I missed a lot of things from the Scala world, including all of the built-in Scala collection methods, and other things as simple as the Scala Tuple classes.

If you haven’t used them before, a Scala Tuple class lets you write code like this:

Tuple<String, Integer> t = new Tuple<>("age", 41);

If you’re comfortable with generics, the Java implementation of a Tuple class like this is simple:

/**
 * @see http://www.javatuples.org/ for a more thorough approach
 */
public class Tuple<A, B> {

    public final A a;
    public final B b;

    public Tuple(A a, B b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Tuple<?, ?> tuple = (Tuple<?, ?>) o;
        if (!a.equals(tuple.a)) return false;
        return b.equals(tuple.b);
    }

    @Override
    public int hashCode() {
        int result = a.hashCode();
        result = 31 * result + b.hashCode();
        return result;
    }
}

Note: I just added the equals and hashCode methods in January, 2017, so I can use my Tuple class as a key in a Java HashMap. I generated the code shown using IntelliJ IDEA.

Technically that should be a Tuple2, as it is a container for two heterogeneous items. Scala has tuple classes that hold anywhere between two and twenty-two items, and they’re named Tuple2 through Tuple22. To do the same thing in Java you would just implement the same pattern for Tuple2 through Tuple22 in Java.

Note that this is just an example implementation of a tuple class. If you prefer the Java getter and setter approach you can add getA() and getB() methods instead of using the implementation shown. (You don’t really want setter methods; the idea is that this little “collection” is immutable.) The current implementation lets you write code like this:

Tuple<String, Integer> t = new Tuple<>("age", 41);
String s = String.format("Your %s is %d", t.a, t.b);
System.out.println(s);

It’s worth noting that there is a Java tuples project, but I could never remember the names that are given to each class, like Septet, Octet, Ennead, and Decade. I prefer Tuple2, Tuple3, and so on.

More resources

If you want to learn more about Scala tuples, please see the following short tutorials:

And for the record, here is a link to the Scala Tuple2 class.