odiseo
odiseo

Reputation: 6784

Groovy: String representing a List to an actual List

Is there a way in Groovy to make a list out of a string? i.e. I have a String "[0,1]" , and I want to transform it to [0,1] (and actual groovy list) in order to manipulate.

The values of the string might be bidimensional ( "[ [1], [2, 3]]" ) but it's for sure it will always be a list.

Upvotes: 0

Views: 140

Answers (1)

tim_yates
tim_yates

Reputation: 171054

You can use Eval.me but obviously, take care of evaluating any old strings

def a = Eval.me( '[ 1, 2 ]' )

An alternative could be:

def a = new groovy.json.JsonSlurper().parseText( '[ 1, 2 ]' )

As the two list forms you give in your question are both valid Json :-)

PERFORMANCE

Given the following benchmarking code:

@Grab('com.googlecode.gbench:gbench:0.4.1-groovy-2.1') // v0.4.1 for Groovy 2.1
import groovy.json.JsonSlurper

def r = benchmark( measureCpuTime:false ) { 
  'eval' {
    def a = Eval.me( '[ 1, 2 ]' )
    assert a == [ 1, 2 ]
  }
  'json' {
    def a = new JsonSlurper().parseText( '[ 1, 2 ]' )
    assert a == [ 1, 2 ]
  }
}
r.prettyPrint()

I get the output:

eval  4661121
json     7257

So it's much quicker going the json route ;-)

Upvotes: 3

Related Questions