Reputation: 18289
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)
{
... ? ...
}
Upvotes: 10
Views: 17876
Reputation: 538
convert String[] to Integer[] in java 8:
Integer[] myArray = Stream.of(new String[] { "1", "2", "3" })
.map(Integer::parseInt)
.toArray(Integer[]::new);
Upvotes: 1
Reputation: 35
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
Upvotes: 1
Reputation: 18289
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();
}
Upvotes: 13
Reputation: 138922
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.
Upvotes: 13
Reputation: 81104
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.
Upvotes: 3