Get the first element of a list idiomatically in Groovy

后端 未结 3 1603
我寻月下人不归
我寻月下人不归 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]
    

提交回复
热议问题