Reputation: 3848
I have a groovy list of CurrencyTypes example
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"))
I want the list of codes as comma separated values like INR, USD, CAD with minimal code and with out creating new list.
Upvotes: 18
Views: 56619
Reputation: 13859
Try currenciesList.code.join(", ")
. It will create list at background, but it's minimal code solution.
Also do you know, that your code may be even Groovier? Look at Canonical or TupleConstructor transformations.
//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(", ")
Upvotes: 44
Reputation: 171054
If you don't want to create a new list (which you say you don't want to do), you can use inject
currenciesList.inject( '' ) { s, v ->
s + ( s ? ', ' : '' ) + v
}
Upvotes: 7
Reputation: 3934
This one works as well:
String s = ""
currenciesList.collect { s += "$it.code," }
assert s == "INR,USD,CAD,"
Upvotes: -1