10

I have a String[], where each element is convertible to an integer. What's the best way I can convert this to an int[]?

int[] StringArrayToIntArray(String[] s)
{
    ... ? ...
}
1
  • Looks an awful lot like homework, apologies if it is not. Commented Aug 9, 2011 at 21:29

5 Answers 5

13
public static int[] StringArrToIntArr(String[] s) {
   int[] result = new int[s.length];
   for (int i = 0; i < s.length; i++) {
      result[i] = Integer.parseInt(s[i]);
   }
   return result;
}

Simply iterate through the string array and convert each element.

Note: If any of your elements fail to parse to an int this method will throw an exception. To keep that from happening each call to Integer.parseInt() should be placed in a try/catch block.

Sign up to request clarification or add additional context in comments.

3 Comments

don't forget the try/catch block
@Woot, the asker specified that each element is convertible to an int so I intentionally omitted it.
You have a } in place of a { at the start of the for loop.
13

Now that Java's finally caught up to functional programming, there's a better answer:

int[] StringArrayToIntArray(String[] stringArray)
{
    return Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
}

Comments

3

With Guava:

return Ints.toArray(Collections2.transform(Arrays.asList(s), new Function<String, Integer>() {
    public Integer apply(String input) {
        return Integer.valueOf(input);
    }
});

Admittedly this isn't the cleanest use ever, but since the Function could be elsewhere declared it might still be cleaner.

Comments

1

This is a simple way to convert a String to an Int.

    String str = "15";
    int i;
    
    i = Integer.parseInt(str);

Here is an example were you to do some math with an User's input:

    int i;
    String input;
    i = Integer.parseInt(str);
    input = JOptionPane.showMessageDialog(null, "Give me a number, and I'll multiply with 2");
    JOptionPane.showMessageDialog(null, "The number is: " + i * 2);

Output:

Popup: A dialog with an input box that says: Give me a number, and I'll multiply it with 2.

Popup: The number is: inputNumber * 2

Comments

1

convert String[] to Integer[] in java 8:

Integer[] myArray = Stream.of(new String[] { "1", "2", "3" })
        .map(Integer::parseInt)
        .toArray(Integer[]::new);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.