• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2990
  • Last Modified:

How to convert a string to list in Groovy

Hi experts,
  I have a requirement to convert a "list-like" string into a real list in Groovy. For example, if I have a string as '[1,2,3,4,5]', how can I write a closure to convert it into a list type as [1,2,3,4,5]? If possible, could you please show me the real code?
  I'm totally new to Groovy and learning it right now.
  Thanks!

Cheers,
Michael
0
michaelzhou23
Asked:
michaelzhou23
  • 2
1 Solution
 
mahomeCommented:
There are likely many of possibilities in groovy. Here is one of them:

// Closure
def convertToList = { it[1..-2].split(',').collect{ it } }
 
// Example-Usage
def string = "[1,2,3,4,5]"
def result = convertToList(string)
 
println result
println result.getClass()
        

Open in new window

0
 
TimYatesCommented:
This will return them as ints...

But as mahome says, there's loads of ways round this
def convertInts = { list ->
  list.tokenize( "[, ]" ).collect { it as Integer }  
}
def iList = convertInts( "[1, 2, 3, 4, 5, 11]" )
iList.each { println "$it (${it.class})" }

Open in new window

0
 
michaelzhou23Author Commented:
Hi Thanks a lot!
I tested them and they worked. But I was wondering whether there is any way that I can put the whole things in one statement? I mean i would need this in a groovy expression.
Thanks!
0
 
TimYatesCommented:
?
"[1,2,3,4,5]".tokenize( "[, ]" ).collect { it as Integer }

Open in new window

0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now