{"id":585,"date":"2014-07-21T07:42:08","date_gmt":"2014-07-21T06:42:08","guid":{"rendered":"http:\/\/benjiweber.co.uk\/blog\/?p=585"},"modified":"2014-07-21T07:42:08","modified_gmt":"2014-07-21T06:42:08","slug":"tuples-in-java","status":"publish","type":"post","link":"https:\/\/benjiweber.co.uk\/blog\/2014\/07\/21\/tuples-in-java\/","title":{"rendered":"Tuples in Java"},"content":{"rendered":"<p class=\"lead\">The absence of tuples in Java is often bemoaned. Tuples are collections of a variety of types. They might look like (&#8220;benji&#8221;,8,&#8221;weber&#8221;) &#8211; 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.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>If we want to return a tuple from a method, by statically importing an &#8220;tuple&#8221; method that is overloaded for each arity of tuple we can do<\/p>\n<pre lang=\"java\">\r\nstatic TriTuple<String, Integer, String> me() {\r\n    return tuple(\"benji\",9001,\"weber\");\r\n}\r\n<\/pre>\n<p>Other than the return type of the method it is fairly concise.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>Using the above method now becomes<\/p>\n<pre lang=\"java\">\r\nString name = me()\r\n    .map((firstname, favouriteNo, surname) -> firstname + \" \" + surname);\r\n\r\nassertEquals(\"benji weber\", name);\r\n<\/pre>\n<p>We can even throw checked exceptions on the consuming side if we allow our map method to accept functions that throw exceptions.<\/p>\n<pre lang=\"java\">\r\nString name = me()\r\n    .map((firstname, favouriteNo, surname) -> {\r\n        if (favouriteNo > 9000) throw new NumberTooBigException();\r\n        return firstname;\r\n    });\r\n<\/pre>\n<p>Of course we&#8217;d also like identical tuples to be equal to each other so that this is true.<\/p>\n<pre lang=\"java\">\r\nassertEquals(tuple(\"hello\",\"world\"), tuple(\"hello\", \"world\"));\r\n<\/pre>\n<p>The implementation looks like this, re-using the <a href=\"http:\/\/benjiweber.co.uk\/blog\/2014\/04\/24\/named-classless-java-value-objects\/\">value-object pattern I described previously<\/a><\/p>\n<pre lang=\"java\">\r\npublic interface Tuple {\r\n    \/\/...\r\n    static <A,B,C> TriTuple<A,B,C> tuple(A a, B b, C c) {\r\n        return TriTuple.of(a, b, c);\r\n    }\r\n    \/\/...\r\n}\r\n\r\npublic interface TriTuple<A,B,C> {\r\n    A one();\r\n    B two();\r\n    C three();\r\n    static <A,B,C> TriTuple<A,B,C> of(A a, B b, C c) {\r\n        abstract class TriTupleValue extends Value<TriTuple<A,B,C>> implements TriTuple<A,B,C> {}\r\n        return new TriTupleValue() {\r\n            public A one() { return a; }\r\n            public B two() { return b; }\r\n            public C three() { return c; }\r\n        }.using(TriTuple::one, TriTuple::two, TriTuple::three);\r\n    }\r\n\r\n    default <R,E extends Exception> R map(ExceptionalTriFunction<A, B, C, R, E> f) throws E {\r\n        return f.apply(one(),two(),three());\r\n    }\r\n\r\n    default <E extends Exception> void consume(ExceptionalTriConsumer<A,B,C,E> consumer) throws E {\r\n        consumer.accept(one(), two(), three());\r\n    }\r\n}\r\n<\/pre>\n<p><a href=\"https:\/\/github.com\/benjiman\/expressions\/tree\/master\/src\/main\/java\/uk\/co\/benjiweber\/expressions\/tuples\">Browse the full code on Github<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The absence of tuples in Java is often bemoaned. Tuples are collections of a variety of types. They might look like (&#8220;benji&#8221;,8,&#8221;weber&#8221;) &#8211; 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&#8230;  <a href=\"https:\/\/benjiweber.co.uk\/blog\/2014\/07\/21\/tuples-in-java\/\" class=\"more-link\" title=\"Read Tuples in Java\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[8],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v14.9 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/benjiweber.co.uk\/blog\/2014\/07\/21\/tuples-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Tuples in Java - Benji&#039;s Blog\" \/>\n<meta property=\"og:description\" content=\"The absence of tuples in Java is often bemoaned. Tuples are collections of a variety of types. They might look like (&#8220;benji&#8221;,8,&#8221;weber&#8221;) &#8211; 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... Read more &raquo;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/benjiweber.co.uk\/blog\/2014\/07\/21\/tuples-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"Benji&#039;s Blog\" \/>\n<meta property=\"article:published_time\" content=\"2014-07-21T06:42:08+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#website\",\"url\":\"https:\/\/benjiweber.co.uk\/blog\/\",\"name\":\"Benji&#039;s Blog\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/benjiweber.co.uk\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/2014\/07\/21\/tuples-in-java\/#webpage\",\"url\":\"https:\/\/benjiweber.co.uk\/blog\/2014\/07\/21\/tuples-in-java\/\",\"name\":\"Tuples in Java - Benji&#039;s Blog\",\"isPartOf\":{\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#website\"},\"datePublished\":\"2014-07-21T06:42:08+00:00\",\"dateModified\":\"2014-07-21T06:42:08+00:00\",\"author\":{\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/benjiweber.co.uk\/blog\/2014\/07\/21\/tuples-in-java\/\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09\",\"name\":\"benji\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/05fb47b31a0b329e1b790074a9b624ef?s=96&d=mm&r=g\",\"caption\":\"benji\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","amp_enabled":true,"_links":{"self":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/585"}],"collection":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/comments?post=585"}],"version-history":[{"count":8,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/585\/revisions"}],"predecessor-version":[{"id":593,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/585\/revisions\/593"}],"wp:attachment":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=585"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=585"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=585"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}