How to convert String into two dimensional array - groovy

How can I convert a string like this
'[["dfd","ewer","errr","ggg"],["yyy","ttt","rrr","ggg"]]'
into a list?
I don't want to use GroovyShell().evaluate()
Thanks

You can use Eval.me like so:
String input = '[["dfd","ewer","errr","ggg"],["yyy","ttt","rrr","ggg"]]'
List output = Eval.me( input )
assert output.size() == 2
assert output*.size() == [ 4, 4 ]
(though of course, under the covers, Groovy just calls GroovyShell.evaluate())
Then for pure Groovy, there's JsonParser:
output = new groovy.json.JsonSlurper().parseText( input )

Related

Elegant way to loop through a list of strings, split each string and output except N first elements

For instance, this list contains the following strings:
array[0]: "text1,text2,text3,text4,text5"
array[1]: "text1,text2,text3,text4,text5,text6,text7"
array[2]: "text1,text2,text3,text4,text5,text6"
I need to ignore the first 3 texts and take the rest.
Output should be:
"text4,text5"
"text4,text5,text6,text7"
"text4,text5,text6"
I suppose I need to split the string using the comma and iterate from 2 till array length for each element.
Is there an elegant way to perform this?
Hi you can use list comprehension
array = ["text1,text2,text3,text4,text5", "text1,text2,text3,text4,text5,text6,text7", "text1,text2,text3,text4,text5,text6"]
result = [i.split(",")[2:] for i in array]
print(result)
For Groovy, you can do something like this:
def input = [
"text1,text2,text3,text4,text5",
"text1,text2,text3,text4,text5,text6,text7",
"text1,text2,text3,text4,text5,text6",
]
def result = input.collect {
it.split(',').drop(3).join(',')
}
result.each { println it }
which prints out
text4,text5
text4,text5,text6,text7
text4,text5,text6
For lovers of 1-liners:
def input = [
"text1,text2,text3,text4,text5",
"text1,text2,text3,text4,text5,text6,text7",
"text1,text2,text3,text4,text5,text6",
]
def output = input*.split(',')*.getAt( 3..-1 )*.join(',')
output.each this.&println
prints:
text4,text5
text4,text5,text6,text7
text4,text5,text6
array = array.collect{ i-> i[3..-1] }
if you want just to print
array.each{ i-> println i[3..-1].join(',') }

Groovy: How to sort String array of text+numbers by last digit

I have array like this:
def arr = [
"v3.1.20161004.0",
"v3.1.20161004.1",
"v3.1.20161004.10",
"v3.1.20161004.11",
"v3.1.20161004.2",
"v3.1.20161004.3",
"v3.1.20161004.30",
]
I need to get this:
def arr = [
"v3.1.20161004.0",
"v3.1.20161004.1",
"v3.1.20161004.2",
"v3.1.20161004.3",
"v3.1.20161004.10",
"v3.1.20161004.11",
"v3.1.20161004.30",
]
How to sort it by last number '.x' ?
You can tokenize each string on . and then grab the last element as an Integer, and sort on this (passing false to return a new list)
def newArray = arr.sort(false) { it.tokenize('.')[-1] as Integer }
When sorting an array you can define a sorting closure. In this case you can split on the dot and sort using the spaceship operator:
arr.sort { a, b -> a.tokenize('.').last().toInteger() <=> b.tokenize('.').last().toInteger() }

Creating maps in Groovy with functions

I am trying to understand if the following Groovy syntax is correct:
String f() { return "Hello"}
String g() { return "World"}
Map myMap = [
a : f(),
b : g(),
]
String x = myMap['a']
String y = myMap['b']
assert x == "Hello"
assert y == "World"
The Groovy language reference documentation on maps is not clear in this regard:
http://docs.groovy-lang.org/latest/html/documentation/index.html#_maps
Yes it's correct. Your case is covered in the first example in the documentation.
def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']
Think of the syntax as something like this: [value: expression]
The keys a and b become strings (value) and the methods are called to evaluate the expressions.

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.
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 ;-)

How to Convert Array into int in groovy?

Lets say I have a array defined in Groovy like this
def int[] a = [1,9]
Now I want to convert this array into a int variable say a1 such that a1 has the value as 19(which are the array values in the a) any way to do this?
I'd go for:
[1, 2, 3, 4].inject(0) { a, h -> a * 10 + h }
1) you don't need the def:
int[] a = [0,9]
2) What do you mean by 09? Isn't that 9? How are you seeing this encoding working?
If you mean you just want to concatenate the numbers together, so;
[ 1, 2, 3, 4 ] == 1234
Then you could do something like:
int b = a.collect { "$it" }.join( '' ) as int
which converts each element into a string, joins them all together, and then parses the resultant String into an int
def sb = new StringBuilder()
[0,9].each{
sb.append(it)
}
assert sb.toString() == "09"
Based on your comments on other answers, this should get you going:
def a = [ 0, 9, 2 ]
int a1 = a.join('') as int​
assert a1 == 92
As you can see from the other answers, there's many ways to accomplish what you want. Just use the one that best fit your coding style.
You already have plenty of options, but just to add to the confusion, here's another one:
int[] a = [1,9]
Integer number = a.toList().join().toInteger()
// test it
assert number == 19

Resources