嘿,我尝试在 groovy 中修剪列表的每个字符串项
list.each() { it = it.trim(); }
但这仅适用于闭包,列表中的字符串仍然是“foo”、“bar”和“groovy”。
我怎样才能做到这一点?
嘿,我尝试在 groovy 中修剪列表的每个字符串项
list.each() { it = it.trim(); }
但这仅适用于闭包,列表中的字符串仍然是“foo”、“bar”和“groovy”。
我怎样才能做到这一点?
list = list.collect { it.trim() }
您还可以使用扩展运算符:
def list = [" foo", "bar ", " groovy "]
list = list*.trim()
assert "foo" == list[0]
assert "bar" == list[1]
assert "groovy" == list[2]
根据Groovy Quick Start, usingcollect
将收集从闭包返回的值。
下面是一个使用 Groovy Shell 的小例子:
groovy:000> ["a ", " b"].collect { it.trim() }
===> [a, b]
如果你真的需要修改列表,你可以使用 list.eachWithIndex { item, idx -> list[idx] = item.trim() }。
collect() 更好。
@sepp2k 我认为这适用于红宝石
这适用于 groovy list = list.collect() { it.trim(); }