Convert a String Array to Integer Array in Java

Learn to convert a specified array of strings to an array of int or Integer values using Java 8 Streams. We will also learn to handle invalid values that cannot be parsed to integers.

1. Converting from String[] to int[]

Java Streams provide a concise way to iterate over array or collection elements, perform intermediate operations and collect the results into an entirely new collection or array.

In this approach, we iterate over the stream of string array, parse each string into int value using Integer::parseInt, and collect int values into a new array.

Notice we are using mapToInt() operation, which ensures we get only the int values to be collected using toArray() method.

String[] strArray = new String[] {"1", "2", "3"};

int[] intArray = Arrays.stream(strArray)
    .mapToInt(Integer::parseInt)
    .toArray();

System.out.println(Arrays.toString(intArray));	//Prints [1, 2, 3]

2. Converting from String[] to Integer[]

The conversion to Integer array is very similar to int array, except do not use the mapToInt() method that returns int array. Rather we use the map() method that returns the Object types and collects such integers to a new Integer array. The array type declaration has been given in toArray(Integer[]::new) method.

String[] strArray = new String[] {"1", "2", "3"};

Integer[] integerArray = Arrays.stream(strArray)
    .map(Integer::parseInt)
    .toArray(Integer[]::new);

System.out.println(Arrays.toString(integerArray));	//Prints [1, 2, 3]

3. Handling Invalid Values

When we receive the string array values from a remote API or database, there are always chances of getting unparsable values. In this case, we must handle the ParseException when we are parsing string values to int values, and determine a default value to denote an invalid value in the integer array.

In the following example, when we get an unparsable String value, we return the integer value -1. You can choose another default value based on your usecase.

String[] invalidStrArray = new String[]{"1", "2", "3", "four", "5"};

int[] intArray = Arrays.stream(invalidStrArray).mapToInt(str -> {
  try {
    return Integer.parseInt(str);
  } catch (NumberFormatException nfe) {
    return -1;
  }
}).toArray();

System.out.println(Arrays.toString(intArray));	//Prints [1, 2, 3, -1, 5]

4. Conclusion

In this short Java tutorial, we learned to convert a String array into Integer array. We can use this technique to parse and collect the string values to other number types, such as long or double.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial