使用 Java 8 将 String Array 转换为 int Array 的最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26313497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:41:03  来源:igfitidea点击:

What's the simplest way to convert a String Array to an int Array using Java 8?

javaarraysjava-8java-stream

提问by Irvin Denzel Torcuato

I'm currently learning how to use Java and my friend told me that this block of code can be simplified when using Java 8. He pointed out that the parseIntArraycould be simplified. How would you do this in Java 8?

我目前正在学习如何使用Java,我的朋友告诉我,使用Java 8 时可以简化这段代码。他指出parseIntArray可以简化。你会如何在 Java 8 中做到这一点?

public class Solution {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] tokens = input.nextLine().split(" ");
        int[] ints = parseIntArray(tokens);
    }

    static int[] parseIntArray(String[] arr) {
        int[] ints = new int[arr.length];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = Integer.parseInt(arr[i]);
        }
        return ints;
    }
}

回答by Boris the Spider

For example:

例如:

static int[] parseIntArray(String[] arr) {
    return Stream.of(arr).mapToInt(Integer::parseInt).toArray();
}

So take a Streamof the String[]. Use mapToIntto call Integer.parseIntfor each element and convert to an int. Then simply call toArrayon the resultant IntStreamto return the array.

因此,采取StreamString[]。使用mapToInt调用Integer.parseInt每个元素,并转换为一个int。然后简单地调用toArray结果IntStream返回数组。

回答by Holger

You may skip creating the token String[]array:

您可以跳过创建令牌String[]数组:

Pattern.compile(" ")
       .splitAsStream(input.nextLine()).mapToInt(Integer::parseInt).toArray();

The result of Pattern.compile(" ")may be remembered and reused, of course.

的结果Pattern.compile(" ")当然可以被记住和重用。

回答by Shirkam

You could, also, obtain the array directly from a split:

您也可以直接从拆分中获取数组:

String input; //Obtained somewhere
...
int[] result = Arrays.stream(input.split(" "))
        .mapToInt(Integer::valueOf)
        .toArray();

Here, Arrayshas some nice methods to obtain the stream from an array, so you can split it directly in the call. After that, call mapToIntwith Integer::valueOfto obtain the IntStreamand toArrayfor your desired int array.

在这里,Arrays有一些很好的方法可以从数组中获取流,因此您可以在调用中直接拆分它。在此之后,调用mapToIntInteger::valueOf获取IntStreamtoArray您所需的int数组。