Does it exist a better way to parse String to Integer using stream than this :
String line = "1 2 3 4 5";
List<Integer> elements = Arrays.stream(line.split(" ")).mapToInt(x -> Integer.parseInt(x))
.boxed().collect(Collectors.toList());
You can eliminate one step if you parse the String directly to Integer:
String line = "1 2 3 4 5";
List<Integer> elements = Arrays.stream(line.split(" ")).map(Integer::valueOf)
.collect(Collectors.toList());
Or you can stick to primitive types, which give better performance, by creating an int array instead of a List<Integer>:
int[] elements = Arrays.stream(line.split(" ")).mapToInt(Integer::parseInt).toArray ();
You can also replace
Arrays.stream(line.split(" "))
with
Pattern.compile(" ").splitAsStream(line)
I'm not sure which is more efficient, though.
There's one more way to do it that will be available since java-9 via Scanner#findAll:
int[] result = scan.findAll(Pattern.compile("\\d+"))
.map(MatchResult::group)
.mapToInt(Integer::parseInt)
.toArray();
map(MatchResult::group) in the returned stream? I mean, I know I can go to the docs and find out, but maybe it's better for future readers if you explain this approach a little bit. Thanks!0. that's what you get when you use group(). if you need another group, you just use group(n). And you are always welcome
int? What if one fails? What should happen then?Integeris wanted,notint, I would useInteger::valueOfto avoidboxed())