Groovy Goodness: Represent Map as String
Clean debug logs are easier with some friendly Groovy functions. This quick tutorial will show you one of the ways Groovy can help.
Join the DZone community and get the full member experience.
Join For FreeSuggested zone: Java
Groovy adds to Map
objects the toMapString
method. With this method we can have a String representation of our Map
. We can specify an argument for the maximum width of the generated String
. Groovy will make sure as many key/value pairs as possible are added as a pair, before adding three dots (...
) if the maximum size is exceeded.
def course = [
name: 'Groovy 101',
teacher: 'mrhaki',
location: 'The Netherlands']
assert course.toMapString(15) == '[name:Groovy 101, ...]'
assert course.toMapString(25) == '[name:Groovy 101, teacher:mrhaki, ...]'
As mentioned in a previous post we can use the toListString
method to represent a List
as a String
:
def names = ['mrhaki', 'hubert']
assert names.toListString(5) == '[mrhaki, ...]'
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