Groovy Goodness: Turn a Map or List as String to Map or List
In Groovy, you can turn a map or list into a string--but how do you change it back? Read on to find out.
Join the DZone community and get the full member experience.
Join For FreeIn a previous post we learned how to use the toListString
or toMapString
methods. With these methods we create a String representation of a List
or Map
object. With a bit of Groovy code we can take such a String
object and turn it into a List
or Map
again.
In the following code snippet we turn the String
value [abc, 123, Groovy rocks!]
to a List
with three items:
// Original List with three items.
def original = ['abc', 123, 'Groovy rocks!']
// Create a String representation:
// [abc, 123, Groovy rocks!]
def listAsString = original.toListString()
// Take the String value between
// the [ and ] brackets, then
// split on , to create a List
// with values.
def list = s2[1..-2].split(', ')
assert list.size() == 3
assert list[0] == 'abc'
assert list[1] == '123' // String value
assert list[2] == 'Groovy rocks!'
We can do something similar for a String
value representing a map structure:
// Original Map structure.
def original = [name: 'mrhaki', age: 42]
// Turn map into String representation:
// [name:mrhaki, age:42]
def mapAsString = original.toMapString()
def map =
// Take the String value between
// the [ and ] brackets.
mapAsString[1..-2]
// Split on , to get a List.
.split(', ')
// Each list item is transformed
// to a Map entry with key/value.
.collectEntries { entry ->
def pair = entry.split(':')
[(pair.first()): pair.last()]
}
assert map.size() == 2
assert map.name == 'mrhaki'
assert map.age == '42'
Written with Groovy 2.4.7.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments