简体   繁体   中英

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

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;
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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