int item = Math.random() * 100000 def doCode = { return 'hi' } Map $_ = [a: 1, b: ['c d': [z: item, doit: doCode]]] use (UtilCategory) { assert $_.dotPath() == [a: 1, b: ['c d': [z: item, doit: doCode]]] assert $_.dotPath('') == [a: 1, b: ['c d': [z: item, doit: doCode]]] assert $_.dotPath(null) == [a: 1, b: ['c d': [z: item, doit: doCode]]] assert $_.dotPath('a') == 1 assert $_.dotPath('b.c d.z') == item assert $_.dotPath('b/c d/z', '/') == item assert $_.dotPath('b.c d.doit')() == 'hi' assert $_.dotPath('b.c d.y') == null assert $_.dotPath('b.c d.z.z') == null assert $_.dotPath('b.c d.z.z.') == null assert 1.dotPath('toString') == null } //======================================== @Category(Object) class UtilCategory { def dotPath(String path = '', String delimiter = /\./) { Object self = this if (!path) return self try { return path.split(/$delimiter/).inject(self) { x, i-> x = x[i] } } catch (Exception ex) { return null } } }
Thursday, January 16, 2014
dotPath
Wednesday, January 15, 2014
collectEntries - List to Map
List a = (1..50).toList() Closure remainder = { return (it % 8) } Map b = a.collectEntries{ i-> [(i.toString()) : remainder(i)]} assert b['5'] == 5 assert b['7'] == 7 assert b['8'] == 0 assert b['17'] == 1 String last = b.keySet()[-1] assert b[last] == 2 // [50:2] a = ('a'..'z').toList() Closure mult = { return (it * 8) } b = a.collectEntries{ i-> [(i.toString()) : mult(i)]} assert b['a'] == 'a'*8 last = b.keySet()[-1] assert b[last] == 'z'*8 // [z:zzzzzzzz]
csv-2-List for groovycsv
@Grab('com.xlson.groovycsv:groovycsv:1.0') import com.xlson.groovycsv.CsvParser // a normally parsed csv can only be searched through ONCE // this is used to create a "re-searchable" object (List of Maps) List csv2List( String filePath, boolean shouldTrim = true ) { new File( filePath ).withReader { r -> new CsvParser().parse( r ).with { csv -> return csv.collect { line -> line.columns.collectEntries { c, v -> [ c, (shouldTrim ? line[ c ].trim() : line[ c ]) ] } } } } }
Subscribe to:
Posts (Atom)