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

你。 提交于 2019-12-04 09:14:40

问题


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

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/26313497/whats-the-simplest-way-to-convert-a-string-array-to-an-int-array-using-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!