Get the first element of a list idiomatically in Groovy

Adam Schmideg picture Adam Schmideg · Jan 29, 2011 · Viewed 38.6k times · Source

Let the code speak first

def bars = foo.listBars()
def firstBar = bars ? bars.first() : null
def firstBarBetter = foo.listBars()?.getAt(0)

Is there a more elegant or idiomatic way to get the first element of a list, or null if it's not possible? (I wouldn't consider a try-catch block elegant here.)

Answer

John Wagenleitner picture John Wagenleitner · Jan 30, 2011

Not sure using find is most elegant or idiomatic, but it is concise and wont throw an IndexOutOfBoundsException.

def foo 

foo = ['bar', 'baz']
assert "bar" == foo?.find { true }

foo = []
assert null == foo?.find { true }

foo = null
assert null == foo?.find { true }  

--Update Groovy 1.8.1
you can simply use foo?.find() without the closure. It will return the first Groovy Truth element in the list or null if foo is null or the list is empty.