我有一个常见的CurrencyTypes示例列表
class CurrencyType
{
int id;
def code;
def currency;
CurrencyType(int _id, String _code, String _currency)
{
id = _id
code = _code
currency = _currency
}
}
def currenciesList = new ArrayList<CurrencyType>()
currenciesList.add(new CurrencyType(1,"INR", "Indian Rupee"))
currenciesList.add(new CurrencyType(1,"USD", "US Dollar"))
currenciesList.add(new CurrencyType(1,"CAD", "Canadian Dollar"))
Run Code Online (Sandbox Code Playgroud)
我希望代码列表以逗号分隔的值(如INR,USD,CAD)和最少的代码以及创建新列表.
Sea*_*ull 31
试试currenciesList.code.join(", ").它将在后台创建列表,但它是最小的代码解决方案.
您也知道,您的代码可能甚至是Groovier吗?查看Canonical或TupleConstructor转换.
//This transform adds you positional constructor.
@groovy.transform.Canonical
class CurrencyType {
int id
String code
String currency
}
def currenciesList = [
new CurrencyType(1,"INR", "Indian Rupee"),
new CurrencyType(1,"USD", "US Dollar"),
new CurrencyType(1,"CAD", "Canadian Dollar")
]
//Spread operation is implicit, below statement is same as
//currenciesList*.code.join(/, /)
currenciesList.code.join(", ")
Run Code Online (Sandbox Code Playgroud)
如果您不想创建新列表(您说您不想这样做),则可以使用 inject
currenciesList.inject( '' ) { s, v ->
s + ( s ? ', ' : '' ) + v
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32920 次 |
| 最近记录: |