简体   繁体   English

Java 将 String[] 转换为 int[]

[英]Java convert String[] to int[]

I have a String[], where each element is convertible to an integer.我有一个 String[],其中每个元素都可以转换为 integer。 What's the best way I can convert this to an int[]?我可以将其转换为 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.注意:如果您的任何元素无法解析为int ,此方法将引发异常。 To keep that from happening each call to Integer.parseInt() should be placed in a try/catch block.为了防止这种情况发生,对Integer.parseInt()的每次调用都应该放在try/catch块中。

Now that Java's finally caught up to functional programming, there's a better answer:现在 Java 终于赶上了函数式编程,有一个更好的答案:

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.诚然,这不是最干净的使用,但由于Function可以在其他地方声明,它可能仍然更干净。

This is a simple way to convert a String to an Int.这是将 String 转换为 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: Output:

Popup: A dialog with an input box that says: Give me a number, and I'll multiply it with 2.弹出:一个带有输入框的对话框,上面写着:给我一个数字,我将它乘以 2。

Popup: The number is: inputNumber * 2弹出:数量为:inputNumber * 2

convert String[] to Integer[] in java 8:将 java 8 中的 String[] 转换为 Integer[]:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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