Reputation: 2308
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.
Upvotes: 3
Views: 694
Reputation: 11822
If you don't mind the result being an Integer[]
:
String s = "1 2 3 4 5";
int[] x = Arrays.stream(s.split(" "))
.mapToInt(Integer::parseInt)
.toArray();
Upvotes: 1
Reputation: 27976
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();
Upvotes: 7