You can convert all elements of a String
array to int
s and store them in an int
array like this:
public static final void main(String[] args) {
String input = "1 2 5 17 23 12 5 72 123 74 13 19 32";
String[] strAr = input.split(" ");
int[] output = parseIntArray(strAr);
}
private static int[] parseIntArray(String[] strAr) {
// convert to int[] one by one
int[] output = new int[strAr.length];
for (int i = 0; i < strAr.length; i++) {
output[i] = Integer.parseInt(strAr[i]);
}
return output;
}
How can you write the parseIntArray(String[])
method in a map-reduce fashion in Java?
I heard that there is a simple way to do this with lambdas in Java 8. Was there also a map-reduce fashion way to do this prior to Java 8? I know this is two questions in one; however I believe that they are so closely related that it is better for the community to have both of these answers on one page.
One way to write it would be:
private static int[] parseIntArray(String[] strAr) {
return Stream.of(strAr).mapToInt(Integer::parseInt).toArray();
}
You could also start directly from the string:
private static final Pattern splitOnSpace = Pattern.compile(" ");
private static int[] parseIntArray(String str) {
return splitOnSpace.splitAsStream(str).mapToInt(Integer::parseInt).toArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With