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?
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;
}
}
You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.
There are several ways to declare and int array: int[] i = new int[capacity]; int[] i = new int[] {value1, value2, value3, etc}; int[] i = {value1, value2, value3, etc};
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.
You may skip creating the token String[] array:
Pattern.compile(" ")
.splitAsStream(input.nextLine()).mapToInt(Integer::parseInt).toArray();
The result of Pattern.compile(" ") may be remembered and reused, of course.
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.
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