-3
def array = [1,2,3,4,5]
def b = int[array.length]
for(int i = 0; i < b.length; i++){
    b[i] = Integer.parseInt(array[i])
}

Should I use Integer.parseInt, Integer.valueOf or other methods?

Should I include a for loop?

Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
Julies GQ
  • 5
  • 3
  • 2
    Does this answer your question? [Integer.valueOf() vs. Integer.parseInt()](https://stackoverflow.com/questions/7355024/integer-valueof-vs-integer-parseint) – Nexevis Feb 13 '20 at 13:44
  • 3
    I'm not sure how the code you posted has anything to do with the title. – Federico klez Culloca Feb 13 '20 at 13:45
  • I obtain a variable which result is the string 1,2,3,4,5 but I need it to be an integer array – Julies GQ Feb 13 '20 at 13:55
  • "I obtain a variable which result is the string 1,2,3,4,5 but I need it to be an integer array" - That is very different than the code sample you included in the question. – Jeff Scott Brown Feb 13 '20 at 17:45
  • It feels like at least once a day, someone asks about how to parse "accidental toString" back into some datastructure. While your question might be totally valid, be double sure, that you don't have to bother with this just because someone did the .toString() or a cast or could not decide for a proper format to transport structured data. – cfrick Feb 14 '20 at 10:30

3 Answers3

2

Instead of this:

def array = [1,2,3,4,5]
def b = int[array.length]
for(int i = 0; i < b.length; i++){
    b[i] = Integer.parseInt(array[i])
}

You could do this:

def array = [1,2,3,4,5]
def b = new int[array.size()]
for(int i = 0; i < b.length; i++){
    b[i] = i
}

You could also do this:

def array = [1,2,3,4,5]
def b = array.toArray(Integer[])
Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
0

In Java 9+, you can stream the matches from a regex:

Pattern.compile("\\d+")
    .matcher(s)
    .results()
    .map(MatchResult::group)
    .map(Integer::parseInt)
    .collect(Collectors.toList());
kaya3
  • 47,440
  • 4
  • 68
  • 97
0

Another option: take all numbers from the string as list and then cast them

"1, 2, 3".findAll(/\d+/) as Integer[]
cfrick
  • 35,203
  • 6
  • 56
  • 68