This post will discuss how to convert a string array to an int array in Java.

1. Using Stream API

If you use Java 8 or above, you can use the static factory method Arrays.stream() to get a Stream for the array, convert each element to an integer using the Integer.parseInt() method, and then call the toArray() method to accumulate the stream elements into an int primitive array.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
Note that the Integer.parseInt() method throws NumberFormatException if the string is not parsable. You can also obtain a stream consisting of elements from the String array using the static factory method Stream.of().

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
If you need an Integer array instead of a primitive int array, you can do like:

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
Finally, if you need a List<Integer> from a String[], you can use collectors to collect the stream elements into a List.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

2. Using Custom Routine

Another solution is to write your own custom method for this easy task, which creates a new array and copy the elements from the original array to the new array after converting each element from string to the integer. A typical implementation for this approach would look like below.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

Note that all the above solutions throw a NumberFormatException if any of the strings does not contain a parsable integer. That’s all about converting a string array to an int array in Java.