8

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());
2
  • 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? Commented Jun 25, 2017 at 13:40
  • "better way" strongly indicates a opinion-based question -- what is better for you? Fastest? less memory? less code? easier to understand? ... ( obviously if Integer is wanted,not int, I would use Integer::valueOf to avoid boxed() ) Commented Dec 19, 2024 at 8:18

2 Answers 2

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.

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

Comments

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();

7 Comments

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!
I fail to see where the line containing the space-separated ints is parsed. Can you point scanners to read from strings?
@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
@tucuxi that's a different way to get those numbers, not by splitting, but by getting all the continuous digits
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.