8

Does it exist 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());
Spongi
  • 501
  • 3
  • 10
  • 19
  • Are you 100% sure that the input string contains space-separated things that can each be parsed to an `int`? What if one fails? What should happen then? – jub0bs Jun 25 '17 at 13:40

2 Answers2

15

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
4

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();
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Hi Eugene! I've seen you've answered at least one similar question using this same approach. Could you please kindly explain why you need to use `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! – fps Jun 25 '17 at 14:23
  • I fail to see where the line containing the space-separated ints is parsed. Can you point scanners to read from strings? – tucuxi Jun 25 '17 at 17:24
  • 1
    @FedericoPeraltaSchaffner it's the first matched group in the regex... with index `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 – Eugene Jun 25 '17 at 17:29
  • 1
    @tucuxi that's a different way to get those numbers, not by splitting, but by getting all the continuous digits – Eugene Jun 25 '17 at 17:32
  • [And in case, you don’t want to wait until Java 9](https://stackoverflow.com/a/37482157/2711488)… – Holger Jun 26 '17 at 17:26
  • @Holger and you are here also... :) – Eugene Jun 26 '17 at 17:30