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)
{
... ? ...
}
The string. split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer. parseInt() method and store that value integer value to the Integer array.
The method generally used to convert String to Integer in Java is parseInt() of String class.
So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With