简体   繁体   中英

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.

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

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
}

This one works as well:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM