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

时间:2014-03-25 22:46:49

标签: 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")) 

我希望代码列表为逗号分隔值,例如INR,USD,CAD,代码最少,无需创建新列表。

3 个答案:

答案 0 :(得分:28)

试试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(", ")

答案 1 :(得分:6)

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

currenciesList.inject( '' ) { s, v ->
    s + ( s ? ', ' : '' ) + v
}

答案 2 :(得分:-1)

这个也适用:

    String s = ""
    currenciesList.collect { s += "$it.code,"  }

    assert s == "INR,USD,CAD,"