1

The list can be empty. I would like to do :

def value = "";
def list = getList()
if (!list.isEmpty()){
   value = list.first().foo 
}

for instance I have found this way :

assert ( [].find()?.foo?:"empty" ) == "empty"
assert ([[foo:"notEmpty1"], [foo:"notEmpty2"]].find()?.foo?:"empty") == "notEmpty1"

Is there a better way ?

Thanks! :)

EDIT:

I got great answer by using [0]

assert ( [][0]?.foo?:"empty" ) == "empty"
assert ([[foo:"notEmpty1"], [foo:"notEmpty2"]][0]?.foo?:"empty") == "notEmpty1"
Nicolas Labrot
  • 4,017
  • 25
  • 40

2 Answers2

0

If it is a List just try

if (!list?.isEmpty()){
    list.get(0);
}

If the list element cannot be null you don't need the ?

If it is a Collection there are several forms to retrieve it. Take a look at this post

Java: Get first item from a collection

Community
  • 1
  • 1
iberbeu
  • 15,295
  • 5
  • 27
  • 48
0

I got an answer from tweeter. The statements :

def value = "";
def list = getList()
if (!list.isEmpty()){
   value = list.first().foo 
}

Can be write :

def value = list[0]?.foo?:""

find may be use if the list can contain null values

Nicolas Labrot
  • 4,017
  • 25
  • 40