Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert a string to an int[] using only lambda expressions?

I was thinking of converting this String: 1 2 3 4 5 6 to an int[] using only lambda expressions. I was thinking of something along the lines of

int[] x = Arrays.asList(scan.nextLine().split(" ")).stream.forEach(it -> Integer.parseInt(it)); but this is syntactically invalid.

like image 885
Berry Avatar asked Jan 24 '26 09:01

Berry


1 Answers

Just a couple of small improvement on @Jason's answer to remove the conversion to list and return an int[] rather than Integer[]:

int[] result = Pattern.compile(" ").splitAsStream("1 2 3 4 5")
    .mapToInt(Integer::parseInt)
    .toArray();
like image 50
sprinter Avatar answered Jan 26 '26 23:01

sprinter