OTUser
OTUser

Reputation: 3848

Groovy Converting List of objects to Comma Separated Strings

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

Answers (3)

Seagull
Seagull

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

tim_yates
tim_yates

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

ludo_rj
ludo_rj

Reputation: 3934

This one works as well:

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

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

Upvotes: -1

Related Questions