Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Tuples With Up to Nine Items [Snippet]

DZone's Guide to

Groovy Goodness: Tuples With Up to Nine Items [Snippet]

With Groovy 2.5.0, we can now create tuples with a maximum of nine items. Let's take a look at how to make use of these new classes.

· Java Zone ·
Free Resource

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

A tuple is an ordered, immutable list of elements. Before Groovy 2.5.0, Groovy supported tuples with one or two elements. Since Groovy 2.5.0, we can now use tuples with a maximum of nine items. Groovy added the classes Tuple3 up to Tuple9. The bonus we get compared to an unmodifiable list with elements is that we can use properties like first, second, third, fourth, fifth, sixth, seventh, eighth, ninth to get items at the specified position.

In the following example, we use all different Tuple classes:

// We can define the types of the elements when we 
// construct a tuple.
def tuple3 = new Tuple3<String, Integer, BigDecimal>('add', 2, 40.0)

// We can use first, second, third properties
// to get values from the tuple.
assert tuple3.first == 'add'
assert tuple3.second == 2
assert tuple3.third == 40.0

// We can use the [index] syntax to get element.
assert tuple3[0] == 'add'  

// Fully typed tuple.
Tuple4<String, Integer, BigDecimal, Integer> tuple4 = 
    new Tuple4<>('subtract', 100, 55.0, 3)

assert tuple4.first == 'subtract'
assert tuple4.second == 100
assert tuple4.third == 55.0
assert tuple4.fourth == 3
assert tuple4[-1] == 3

// With subTuple we can get subsequent
// values from the tuple as a new tuple.
assert tuple4.subTuple(2, tuple4.size()) == new Tuple2<BigDecimal, Integer>(55.0, 3)

// We can imagine how to work with Tuple4..Tuple8 :-)
// ...

// Finally a tuple with 9 items.
def tuple9 = new Tuple9('Groovy', 'rocks', 'and', 'is', 'fun', 'to', 'use', 'as', 'language')

assert tuple9.fifth == 'fun'
assert tuple9.sixth == 'to'
assert tuple9.seventh == 'use'
assert tuple9.eighth == 'as'
assert tuple9.ninth == 'language'

// Tuple extends AbstractList, so we can
// use all methods from List as well.
assert tuple9.join(' ') == 'Groovy rocks and is fun to use as language'

Written with Groovy 2.5.0.

Use this tool to look at the contents of GitHub and classify code based on the programming language used.  Content provided by IBM Developer.

Topics:
java ,groovy ,tuples ,elements ,list ,immutable

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}