19

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

3 Answers 3

47

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Wow! Is this java? Certainly this is tidier than my solution. Thank you for the fast response!
@IrvinDenzelTorcuato Java 8, yes.
@MohammadFaisal it's Java 8 syntax, read about it in the tutorial.
How do you get it as Integer[] array instead of int[] array?
What have you tried @Ridhuvarshan? Why didn't it work?
|
20

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.

1 Comment

Wow, nifty. Didn't know splitAsStream.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.