简体   繁体   中英

How to append comma separated value dynamically in groovy

I've comma separated values which I want to iterate and append the value dynamically like below:

def statusCode = '1001,1002,1003'

Output should look like this:

[item][code]=1001|[item][code]=1002|[item][code]=1003

If statusCode has only two value. For example:

def statusCode = '1001,1002'

Then output should be

[item][code]=1001|[item][code]=1002

I tried something like below since I'm new to groovy not sure how can achieve this with some best approach:

    def statusCode= '1001,1002,1003'
    String[] myData = statusCode.split(",");
    def result
    for (String s: myData) {
        result <<= "[item][code]="+s+"|"
    }
    System.out.println("result :" +result);

You can use collect and join to simplify the code:

def result = statusCode.split(',').collect{"[item][code]=$it"}.join('|')

That returns [item][code]=1001|[item][code]=1002|[item][code]=1003

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