MonkeyMonkey MonkeyMonkey - 7 months ago 36
Groovy Question

Java/Groovy: Create and read a list of two objects

How do I define and iterate over a list of two objects (Foo, Bar)?

What I tried:

// create
def fooBar = new ArrayList<Foo, Bar>()
fooBar.add(new Foo())
fooBar.add(new Bar())
fooBar.add(new Foo()) // << shouldn't be allowed or overwrite first foo

def fooBars = new ArrayList<List<Foo, Bar>>()
fooBars << fooBar

// read
fooBars.each { fooBar ->
def foo = fooBar[0]
def bar = fooBar[1]
// do something with foo and bar

What I want:

// pseudo code
def fooBar = new ???<Foo, Bar>()
fooBar.set(new Foo())
fooBar.set(new Bar())

def fooBars = new ArrayList<???>()
fooBars << fooBar

fooBars.each { fooBar ->
def foo = fooBar[???] // 0, 'foo', ..?
def bar = fooBar[???]
// do something with foo and bar

If creating my own FooBar class is the solution I'm fine, I just hope there is a more simple solution.


Groovy has the notion of Tuples.

def tuple = new Tuple('one', 1)
def (String a, Integer b) = tuple
println a
println b

or alternatively

def doSomething(String s, Integer i) {
  println s
  println i

or alternatively

def doSomething(Tuple t) {
  println t[0]
  println t[1]

then you can do

def tuples = [ ] << tuple << tuple
tuples.each { doSomething(it) }