Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first element of a list idiomatically in Groovy

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.)

like image 959
Adam Schmideg Avatar asked Jan 29 '11 22:01

Adam Schmideg


People also ask

Which method is used to get the first element?

getFirst() method is used to fetch or retrieve the first element from a LinkedList or the element present at the head of the List. As we all know that getFirst() is one of the methods been there up present inside LinkedList class.

Which are the correct ways to define a List in Groovy?

In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. A List literal is presented as a series of objects separated by commas and enclosed in square brackets.

How do I add one List to a List in Groovy?

Combine lists using the plus operator The plus operator will return a new list containing all the elements of the two lists while and the addAll method appends the elements of the second list to the end of the first one. Obviously, the output is the same as the one using addAll method.


1 Answers

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.

like image 108
John Wagenleitner Avatar answered Oct 27 '22 17:10

John Wagenleitner