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

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


posted @ 2021-03-07 10:05  研究林纳斯写的  阅读(787)  评论(0编辑  收藏  举报