learn groovy
learn groovy

Reputation: 527

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

Upvotes: 0

Views: 1215

Answers (1)

ernest_k
ernest_k

Reputation: 45339

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

Upvotes: 1

Related Questions