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
Share:
14,439

Related videos on Youtube

Kyle
Author by

Kyle

Updated on February 21, 2020

Comments

  • Kyle
    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
    tim_yates over 13 years
    But watch out for negative indices which will cause an exception, ie: def a = [] ; println a[ -1 ] throws a java.lang.ArrayIndexOutOfBoundsException
  • Samuel Parsonage
    Samuel Parsonage over 9 years
    @tim_yates any idea why? seems rather inconsistent.
  • Anentropic
    Anentropic about 8 years
    an 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
    doelleri about 6 years
    This throws an IndexOutOfBoundsException if the index is indeed out of bounds, which is actually worse than the current behavior for myarray[400] which returns null.
  • Dave Gorman
    Dave Gorman about 6 years
    Actually, you're right. However myarray?.getAt(400) will return null if out of bounds.
  • doelleri
    doelleri about 6 years
    For what version of Groovy? I've tested with 2.4.13, 2.4.6, 2.0.0, and 1.7.8.
  • Naeel Maqsudov
    Naeel Maqsudov about 5 years
    This is not correct. The ? could only help if myarray is null. If myarray 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
    Alex over 4 years
    Please note, that: test[100] returns null, BUT test.get(100) throws IndexOutOfBoundsException. The same for test?.get(100)