Ant's
Ant's

Reputation: 13811

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?

Upvotes: 3

Views: 8278

Answers (5)

Dónal
Dónal

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

deluan
deluan

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

julx
julx

Reputation: 9091

I'd go for:

[1, 2, 3, 4].inject(0) { a, h -> a * 10 + h }

Upvotes: 7

moritz
moritz

Reputation: 5224

def sb = new StringBuilder()
[0,9].each{
    sb.append(it)
}
assert sb.toString() == "09"

Upvotes: 2

tim_yates
tim_yates

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

Related Questions