Method to convert string array to integer array in Java


Thanks to my friend to ask this question, hence this blog after long gap.
In Java , almost all code logics are processing in terms of objects. However some one new to java is not aware of this initially. For basic java learners, this blog will be helpful for understanding the array logic. Also java does not have any api’s to do this array conversion.
Lets explain the method.

  • input param is string array.
  • allocate sufficient memory for integer array intarray to store the converted value. - int intarray[] = new int[sarray.length];
  • finally iterate the string array values one by one and convert each value into an integer type.
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
int intarray[] = new int[sarray.length];
for (int i = 0; i < sarray.length; i++) {
intarray[i] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}

Note : like this you can convert string in to any available data types(float , double,…) of  which you want.

About these ads

Tags: , , , ,

17 Responses to “Method to convert string array to integer array in Java”

  1. Leena Says:

    What if i have to convert a string array to integer array without using any loop? Is there any method or combination of methods, which does this task?

    Thanks.

  2. manikandanmv Says:

    Leena,

    No way, from my knowledge looping logic is the only methodology to do this task.

  3. Saranya Says:

    I am trying to convert String array to Integer array..

    I am using the following snippet.. Is there any better way?

    public Long[] ConvetStringArrayToLongArray(String[] stringArray){
    ArrayList longList = new ArrayList();

    for(String str : stringArray){
    longList.add(new Long(longList));
    }

    Long[] longArray = longList.toArray(new Long[0]);

    return longArray;
    }

  4. manikandanmv Says:

    Saranya,

    for array type conversion. don’t know about the BEST way except looping logic.

    seems to be your pasted code snippets returns lots of complitation errors and mismatch between your question(integer type) n snippet(long type).
    anyway k. when comparing with my method. I would say my method consume lesser execution time in performance wise.
    you also using the same loop logic, but the difference is you are storing into arraylist and converting into array. this will take more time while execution.
    lets explain clearly.
    first, iterate the string array and store it into arraylist.
    second, using toArray method converting array list to array by that time compiler converting to specified target type which was specified in toArray argument.

    my point is toArray method will internally do some looping process. so your code looks like having two loop’s unnecessarily for just converting array type.

    sometimes our java code looks simple but lacks performance when its going to process huge data.

    hope you understand it. If not post your doubt.

  5. Saranya Says:

    Sorry in stead of Long array i typed Integer on the hurry..

    And i haven’t used that function directly in my code. (thats the case of those compilation errors). i am constructing that ArrayList on the flow of my code (that is, it will get String elements from several String arrays and combine it in one ArrayList then convent all to Long array). To use ur code i need to know the exact size of String elements that will not be known initially in my case. Now I found a logic to calculate the array size of the strings used in my application. and using ur logic.

    ur explanation is very helpful.

    Well.. thanks for your comment..

    • manikandanmv Says:

      noprobs.
      good, anyway you are going to convert array type then y r u using arraylist as temporary storage of all array values coming from several areas, unless/until if any dynamic addition will happen.
      based on your requirements might be you have to change the logic but better keep the performance as one main factor in mind when you write the code.

      thanks for your understanding.

  6. Rendra Kurniawan Says:

    thanks … it’s so help me … thanks a lot

  7. anik Says:

    thnx..

  8. Sean Says:

    what if it is a two dimensional array?
    how can i convert it from string array to int array?

    • manikandanmv Says:

      Sean,
      You have to use two for loops(one for row & another one for column) to iterate and convert the array data.

  9. Muzzamil Says:

    Good discussion friends.. Really helpful for starters like me… :)

  10. Marcin Says:

    A shorter version:

    new ArrayList() {{ for (String tempLongString : tempLongStrings) { add(new Long(tempLongString));}}.toArray(new Long[tempLongStrings.length]));

  11. Murtuza Says:

    how do i convert the string contents of a txt file to an array of integers. please help .
    import java.io.*;
    class FileRead
    {
    public static void main(String args[])
    {
    try{
    FileInputStream in = new FileInputStream(“tex.txt”);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String strLine;
    String[] myarray= new String[10];

    for (int j = 0; j < 10; j++)
    {
    myarray[j] = br.readLine();
    System.out.println(myarray[j]);

    }

    in.close();

    }catch (Exception e){
    System.err.println("Error: " + e.getMessage());
    }
    }
    }

  12. Murtuza Says:

    how do i read the elements of a file and convert it to string and sort it using bubble sort.. please help me make changes to the code
    import java.io.*;
    class Main
    {
    public static void main(String args[])throws IOException
    {
    try{

    FileInputStream in = new FileInputStream(“tex.txt”);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String strLine;
    String[] myarray;
    myarray = new String[10];

    while ((strLine = br.readLine()) != null) {

    for (int j = 0; j < myarray.length; j++){
    myarray[j] = br.readLine();
    }

    }
    in.close();
    int n=10;
    int abc[]=new int[10];

    abc= convertStringArraytoIntArray(myarray);
    for(int o=0;o<10;o++)
    {
    System.out.println(abc[o]);
    }

    bubble(abc,n);
    } catch(Exception e){}
    }

    public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception {

    if (sarray != null) {

    int intarray[] = new int[sarray.length];

    for (int i = 0; i < sarray.length; i++) {

    intarray[i] = Integer.parseInt(sarray[i]);

    }

    return intarray;

    }

    return null;

    }

    public static void bubble( int a[], int n )
    {
    int i, j,t=0;
    for(i = 0; i < n; i++)
    {
    for(j = 1; j a[j])
    {
    t = a[j-1];
    a[j-1]=a[j];
    a[j]=t;
    }

    }
    }

    System.out.println(“the sorted array:”);
    for(i=0;i<n;i++)
    {
    System.out.println(a[i]);
    }
    }
    }

  13. I4P Says:

    thanks.i used this to convert to float! very helpful!!

  14. Karthik Says:

    A much shorter version:

    return Arrays.asList(stringArray).toArray(new Integer[stringArray.length]);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: