Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert String[] to int[]

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)
{
    ... ? ...
}
like image 688
Jay Sullivan Avatar asked Aug 09 '11 21:08

Jay Sullivan


People also ask

How do you convert an array of strings to an array of integers in Java?

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.

How do I convert a string to an integer?

The method generally used to convert String to Integer in Java is parseInt() of String class.

Can we convert string [] to string?

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.


2 Answers

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();
}
like image 121
Jay Sullivan Avatar answered Oct 05 '22 23:10

Jay Sullivan


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.

like image 22
Mark Peters Avatar answered Oct 06 '22 00:10

Mark Peters