Reputation: 13811
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?
Upvotes: 3
Views: 8278
Reputation: 187537
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
Upvotes: 0
Reputation: 1865
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.
Upvotes: 1
Reputation: 5224
def sb = new StringBuilder()
[0,9].each{
sb.append(it)
}
assert sb.toString() == "09"
Upvotes: 2
Reputation: 171114
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
Upvotes: 3