使用 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
What's the simplest way to convert a String Array to an int Array using Java 8?
提问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 parseIntArray
could 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 Stream
of the String[]
. Use mapToInt
to call Integer.parseInt
for each element and convert to an int
. Then simply call toArray
on the resultant IntStream
to return the array.
因此,采取Stream
的String[]
。使用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, Arrays
has some nice methods to obtain the stream from an array, so you can split it directly in the call. After that, call mapToInt
with Integer::valueOf
to obtain the IntStream
and toArray
for your desired int array.
在这里,Arrays
有一些很好的方法可以从数组中获取流,因此您可以在调用中直接拆分它。在此之后,调用mapToInt
与Integer::valueOf
获取IntStream
和toArray
您所需的int数组。