-->
Skip to main content

Convert String Array to int array in java [2021]

Convert String Array to int array in java [2021]

In today's programming world, We generally need to Convert String Array to int Array in Java, In this tutorial, we will cover how to convert String Array to int Array in Java using two approaches.
  1. Using the Integer.parseInt method of Integer class.
  2. Using the Stream API of Java 8. 
Convert String array to int array in javaEarlier we have covered different conversions like Convert to String from Byte Array In JavaConvert String to Byte Array in Java and Convert Between Java Byte Array to Object In Java, Convert String to Array In Java which is also similar to our current requirement.

Let's dive in for our current tutorial...

Convert String Array to int Array

 1. Using Integer.parseInt method with for loop

    We can convert String array to int array simply iterating one element at a time and then parsing that element to int form with the help of Integer.parseInt method. 

String array to int array

Example :

 import java.util.Arrays;

 public class StringArrayToIntArray {
   public static void main(String[] args) {
	//String array 
	String strArray[] = {"11","22","33","44","55"};
	// Initializing int array with size equal to string array
	int intArray[] = new int[strArray.length];
	//Converting string array to int array 
	for (int j = 0; j < intArray.length; j++) {
			intArray[j] = Integer.parseInt(strArray[j]);
	}
	//Printing all int array elements
	System.out.println(Arrays.toString(intArray));
   }
 }

Output:

 [11, 22, 33, 44, 55]

 2. Using Integer.parseInt with Stream API

    This approach doesn't use a loop as earlier and uses Java 8 Stream API to convert string array to int array with ease.

String array to int array java 8

Example :

 import java.util.Arrays;
 import java.util.stream.Stream;

 public class StringArrayToIntArrayUsingStream {
   public static void main(String[] args) {
	//String array 		
	String strArray[] = { "11", "22", "33", "44", "55" };
	//Converting string array to int array using Stream with java 8
	int intArray[] = Stream.of(strArray).mapToInt(s->Integer.parseInt(s)).toArray();
	//Printing int array
	System.out.println(Arrays.toString(intArray));
   }
 }

Output:

 [11, 22, 33, 44, 55]

Conclusion:

In this tutorial, we have covered how to convert String Array to int Array in Java using two strategies
  1. Using the Integer.parseInt method of Integer class.
  2. Using the Stream API of Java 8. 

Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions, doubts, suggestions, or feedback then please drop a comment and I'll try to answer your question.

So what do you think about this simple process to Convert String Array to int Array In Java? It's Easy Right?

Happy Learning!!!

More Examples you may like

Comments