简体   繁体   English

Groovy collect()闭包无法大写字符串

[英]Groovy collect() closure not working to capitalize strings

I have a list of objects that are not necessarily a string, and I want to return a list of strings that have been capitalized. 我有一个不一定是字符串的对象列表,并且我想返回一个已经大写的字符串列表。

Currently, I'm doing this: 目前,我正在这样做:

// Input : ["foo", "bar"] (not actually strings)
// Expected Output : ["Foo", "Bar"]
// Actual Output : ["foo", "bar"]

// Code: 
list.collect { it.toString().capitalize() }

What might be the problem? 可能是什么问题? If I print out each element as I go trough collect it prints the correct values, but the final list is wrong. 如果我在收集时打印出每个元素,它将打印正确的值,但是最终列表是错误的。

collect doesn't mutate the original list, but returns a new one: collect不会改变原始列表,但会返回一个新列表:

def oringinal = ["foo", "bar"]
def capitalized = original.collect { it.capitalize() }
println(capitalized) // ["Foo", "Bar"]

PS: you can also use the *. PS:您也可以使用*. spread-dot operator like so: 散点运算符如下所示:

def capitalized = original*.capitalize()

You suspect that .collect() method mutates input list, but it does not - it creates a copy of the list and does not change anything in the input list. 您怀疑.collect()方法会改变输入列表,但不会 -会创建列表的副本,并且不会更改输入列表中的任何内容。

def list = ["foo", "bar"]

def newList = list.collect { it.toString().capitalize() }

assert list != newList

assert newList == ["Foo", "Bar"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM