MonkeyMonkey MonkeyMonkey - 1 month ago 10
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.

Answer

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
}
doSomething(tuple)

or alternatively

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

then you can do

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