定義列表(def)
def foo = [] def myList = ["Apple", "Banana", "Orange"] println myList.class // class java.util.ArrayList
連接兩個列表(+)
def first = ["a", "b", "c"] def second = ["d", "e", "f"] assert ["a", "b", "c", "d", "e", "f"] == (first + second)
彈出與壓入(push & pop)
// pop def list = ["a", false, 2] assert list.pop() == 'a' assert list == [false, 2] // push def list = [3, 4, 2] list.push("x") assert list == ['x', 3, 4, 2]
將元素添加到最開始(add 0)
list.add(0, element)
打印列表(格式化輸出、調試)
import static groovy.json.JsonOutput.* def config = ['test': 'lalala'] println prettyPrint(toJson(config))
遍歷集合,以生成新集合(collect/find/findAll)
def lst = [1,2,3,4]; def newlst = lst.collect {element -> return element * element} println(newlst);
如果 Closure 沒有返回,則會存在 null 元素。使用 newlst.findAll { it != null } 過濾。
相關文章
「Groovy」- 常用字符串操作(String)
「Groovy」- 常用 MAP 操作
參考文獻
Java ArrayList insert element at beginning example
Combine two lists
A simple way to pretty print nested lists and maps in Groovy.
Groovy List Tutorial And Examples
List (Groovy JDK enhancements)
Groovy - collect() - Tutorialspoint
groovy - Remove null and empty values using collect with string array - Stack Overflow
Remove null items from a list in Groovy - Stack Overflow