In Groovy, Is there any way to safely index into a Collection similar to the safe navigation operator?
14,439
That's the default behavior with all collections except arrays in groovy.
assert [1,2,3,4][5] == null
def test = new ArrayList()
assert test[100] == null
assert [1:"one", 2:"two"][3] == null
If you've got an array, cast it to a list.
def realArray = new Object[4]
realArray[100] // throws exception
(realArray as List)[100] // null
You can string list and map indexes together with the ?
operator in the same way as with properties:
def myList = [[name: 'foo'], [name: 'bar']]
assert myList[0]?.name == 'foo'
assert myList[1]?.name == 'bar'
assert myList[2]?.name == null
Related videos on Youtube
Author by
Kyle
Updated on February 21, 2020Comments
-
Kyle about 4 years
This will safely return null without throwing any exceptions
obj?.prop1?.prop2
How can I do that for collections, where it won't throw an index out of bounds exception?
myarray[400] //how do I make it return null if myarray.size() < 400
Is there such an operator for Collections?
-
tim_yates over 13 yearsBut watch out for negative indices which will cause an exception, ie:
def a = [] ; println a[ -1 ]
throws ajava.lang.ArrayIndexOutOfBoundsException
-
Samuel Parsonage over 9 years@tim_yates any idea why? seems rather inconsistent.
-
Anentropic about 8 yearsan addendum for any groovy noobs like my looking for this, if you need to do map access for variable key names you can use this syntax to take advantage of null-safe operator:
mymap = null
keyName = "WTF"
mymap?."$keyName"
-
doelleri about 6 yearsThis throws an
IndexOutOfBoundsException
if the index is indeed out of bounds, which is actually worse than the current behavior formyarray[400]
which returnsnull
. -
Dave Gorman about 6 yearsActually, you're right. However myarray?.getAt(400) will return null if out of bounds.
-
doelleri about 6 yearsFor what version of Groovy? I've tested with 2.4.13, 2.4.6, 2.0.0, and 1.7.8.
-
Naeel Maqsudov about 5 yearsThis is not correct. The
?
could only help ifmyarray
is null. Ifmyarray
is null then calculation of the expression terminates. Otherwise it continuous and tries to access to 400th item which is not exists. And we will get an exception. -
Alex over 4 yearsPlease note, that:
test[100]
returnsnull
, BUTtest.get(100)
throwsIndexOutOfBoundsException
. The same fortest?.get(100)