String Groovy collect()闭包无法将字符串大写
我有一个不一定是字符串的对象列表,我想返回一个已大写的字符串列表 目前,我正在这样做:String Groovy collect()闭包无法将字符串大写,string,groovy,closures,String,Groovy,Closures,我有一个不一定是字符串的对象列表,我想返回一个已大写的字符串列表 目前,我正在这样做: // Input : ["foo", "bar"] (not actually strings) // Expected Output : ["Foo", "Bar"] // Actual Output : ["foo", "bar"] // Code: list.collect { it.toString().capitalize() } 有什么问题吗?如果我在收集过程中打印出每个元素,它会打印出正确
// Input : ["foo", "bar"] (not actually strings)
// Expected Output : ["Foo", "Bar"]
// Actual Output : ["foo", "bar"]
// Code:
list.collect { it.toString().capitalize() }
有什么问题吗?如果我在收集过程中打印出每个元素,它会打印出正确的值,但最终的列表是错误的。您怀疑
.collect()
方法会改变输入列表,但它不会改变输入列表中的任何内容
def list = ["foo", "bar"]
def newList = list.collect { it.toString().capitalize() }
assert list != newList
assert newList == ["Foo", "Bar"]
您怀疑
.collect()
方法会对输入列表进行变异,但它不会——它会创建列表的副本,并且不会更改输入列表中的任何内容
def list = ["foo", "bar"]
def newList = list.collect { it.toString().capitalize() }
assert list != newList
assert newList == ["Foo", "Bar"]
collect
不会改变原始列表,但会返回一个新列表:
def oringinal = ["foo", "bar"]
def capitalized = original.collect { it.capitalize() }
println(capitalized) // ["Foo", "Bar"]
PS:您也可以使用*。
扩展点运算符,如下所示:
def capitalized = original*.capitalize()
collect
不会改变原始列表,但会返回一个新列表:
def oringinal = ["foo", "bar"]
def capitalized = original.collect { it.capitalize() }
println(capitalized) // ["Foo", "Bar"]
PS:您也可以使用*。
扩展点运算符,如下所示:
def capitalized = original*.capitalize()