Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
}
like image 495
Irvin Denzel Torcuato Avatar asked Oct 11 '14 10:10

Irvin Denzel Torcuato


People also ask

How do you convert an array of strings to int arrays in java?

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.

How do you create an array in java 8?

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


3 Answers

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.

like image 165
Boris the Spider Avatar answered Oct 02 '22 00:10

Boris the Spider


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.

like image 33
Holger Avatar answered Oct 01 '22 22:10

Holger


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.

like image 37
Shirkam Avatar answered Oct 01 '22 22:10

Shirkam