简体   繁体   中英

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)
{
    ... ? ...
}
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.

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM