1. 问题描述
该笔记将记录:在 Apache Groovy 中,常用 List 操作,以及常见问题处理。
2. 解决方案
2.1. 定义列表(def)
def foo = []
def myList = ["Apple", "Banana", "Orange"]
println myList.class // class java.util.ArrayList
2.2. 基本操作(增删改查)
增:向 List 中添加元素
list.add(element)
// 将元素添加到最开始
list.add(0, element)
// 连接两个列表
["a", "b", "c"] + ["d", "e", "f"]
删:移除 List 中的元素
lst.remove(2) // 删除第 3 个元素
改:修改 List 中的元素:
list.set(2, 11) // 将第 3 个元素修改为 10
// 获取子列表
list.subList(2, 5) // 获取第 3 到 5 间的元素
查:获取 List 中的元素
list[2]
list.get(2)
list.getAt(2)
// 获取首个元素或最后的元素
list.first()
list.last()
3. 弹出与压入( 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]
4. 打印列表(格式化输出、调试)
// 直接打印
pritln list
// 美化打印
import static groovy. json .JsonOutput.*
def config = ['test': 'lalala']
println prettyPrint(toJson(config))
5. 遍历列表,以生成新列表(collect/find/findAll)
def lst = [1, 2, 3, 4]
def newlst = lst.collect {element -> return element * element}
println(newlst) // [1, 4, 9, 16]
如果 Closure 没有返回,则会存在 null 元素。使用 findAll 过滤:
newlst.findAll { it != null }
6. 参考文献
A simple way to pretty print nested lists and maps in Groovy.()
Combine two lists()
Groovy – collect() – Tutorialspoint()
Groovy Goodness: Getting the First and Last Element of an Iterable – Messages from mrhaki()
Groovy List Tutorial And Examples()
groovy – Remove null and empty values using collect with string array – Stack Overflow()
Java ArrayList insert element at beginning example()
List (Groovy JDK enhancements)()
Remove null items from a list in Groovy – Stack Overflow()
Groovy – subList() – Tutorialspoint()