Get the first element of a list idiomatically in Groovy

后端 未结 3 1604
我寻月下人不归
我寻月下人不归 2020-12-30 21:00

Let the code speak first

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

相关标签:
3条回答
  • 2020-12-30 21:37

    Since Groovy 1.8.1 we can use the methods take() and drop(). With the take() method we get items from the beginning of the List. We pass the number of items we want as an argument to the method.

    To remove items from the beginning of the List we can use the drop() method. Pass the number of items to drop as an argument to the method.

    Note that the original list is not changed, the result of take()/drop() method is a new list.

    def a = [1,2,3,4]
    
    println(a.drop(2))
    println(a.take(2))
    println(a.take(0))
    println(a)
    
    *******************
    Output:
    [3, 4]
    [1, 2]
    []
    [1, 2, 3, 4]
    
    0 讨论(0)
  • 2020-12-30 21:57

    You could also do

    foo[0]
    

    This will throw a NullPointerException when foo is null, but it will return a null value on an empty list, unlike foo.first() which will throw an exception on empty.

    0 讨论(0)
  • 2020-12-30 22:01

    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.

    0 讨论(0)
提交回复
热议问题