Converting String Array to an Integer Array

219,882

Solution 1

You could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like

String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
   // Note that this is assuming valid input
   // If you want to check then add a try/catch 
   // and another index for the numbers if to continue adding the others (see below)
   numbers[i] = Integer.parseInt(numberStrs[i]);
}

As YoYo's answer suggests, the above can be achieved more concisely in Java 8:

int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();  

To handle invalid input

You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.

If you don't need to know about invalid input but just want to continue parsing the array you could do the following:

int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
    try
    {
        numbers[index] = Integer.parseInt(numberStrs[i]);
        index++;
    }
    catch (NumberFormatException nfe)
    {
        //Do nothing or you could print error if you want
    }
}
// Now there will be a number of 'invalid' elements 
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);

The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.

Results in

Input: "2,5,6,bad,10"
Output: [2,3,6,10]

If you need to know about invalid input later you could do the following:

Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)        
{
    try 
    {
        numbers[i] = Integer.parseInt(numberStrs[i]);
    }
    catch (NumberFormatException nfe)   
    {
        numbers[i] = null;
    }
}

In this case bad input (not a valid integer) the element will be null.

Results in

Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]


You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.

Solution 2

Line by line

int [] v = Stream.of(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

Solution 3

Stream.of().mapToInt().toArray() seems to be the best options.

int[] arr = Stream.of(new String[]{"1", "2", "3"})
                  .mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));

Solution 4

For Java 8 and higher:

    String[] test = {"1", "2", "3", "4", "5"};
    int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();

Solution 5

Converting String array into stream and mapping to int is the best option available in java 8.

    String[] stringArray = new String[] { "0", "1", "2" };
    int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(intArray));
Share:
219,882
Mario
Author by

Mario

Updated on February 05, 2021

Comments

  • Mario
    Mario over 3 years

    so basically user enters a sequence from an scanner input. 12, 3, 4, etc.
    It can be of any length long and it has to be integers.
    I want to convert the string input to an integer array.
    so int[0] would be 12, int[1] would be 3, etc.

    Any tips and ideas? I was thinking of implementing if charat(i) == ',' get the previous number(s) and parse them together and apply it to the current available slot in the array. But I'm not quite sure how to code that.

  • Euridice01
    Euridice01 over 9 years
    Java Devil, what do you mean by this "// and another index for the numbers if to continue adding the others"? What if I want to add the others to the array?
  • Java Devil
    Java Devil over 9 years
    @Euridice01 It was merely a suggestion to deal with invalid input. Consider the input 4,6,z,10. Here the z would cause a NumberFormatException so if continued using i as the index there would be a null at the third position in the Integer Array. It just depends on how you want to deal with that scenario. The extra index I was talking about was to just ignore the z so in the final Integer array, the third number would be 10.
  • Evgeny Mamaev
    Evgeny Mamaev over 3 years
    Which package and class is it?
  • Mavaddat Javid
    Mavaddat Javid about 3 years
    @EugeneMamaev it is in org.alfonz.utility github.com/petrnohejl/Alfonz/blob/…