Groovy将对象列表转换为逗号分隔字符串

Ran*_*aul 13 groovy

我有一个常见的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吗?查看CanonicalTupleConstructor转换.

//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)

  • 习惯`currencyList*.code`会很有趣,因为自动列表扩展[可能会被删除](http://docs.codehaus.org/display/GroovyJSR/GEP+11+-+Groovy+3+语义+和+新+ MOP#GEP11-Groovy3semanticsandnewMOP-Removingautomaticlistexpansion) (3认同)
  • 你赢了一些,你输了一些。 (2认同)

tim*_*tes 7

如果您不想创建新列表(您说您不想这样做),则可以使用 inject

currenciesList.inject( '' ) { s, v ->
    s + ( s ? ', ' : '' ) + v
}
Run Code Online (Sandbox Code Playgroud)