「Groovy」- 常用列表操作(List)

更新日期:2021年02月14日

定义列表(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)

def lst = [1,2,3,4];
def newlst = lst.collect {element -> return element * element}
println(newlst);

如果 Closure 没有返回,则会存在 null 元素。使用 newlst.findAll { it != null } 过滤。

参考文献

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


ToC

定义列表(def)

连接两个列表(+)

弹出与压入(push & pop)

将元素添加到最开始(add 0)

打印列表(格式化输出、调试)

遍历集合,以生成新集合(collect)

参考文献