1

I'm having a hard time understanding why this code returns an Object[] and not an int[] ("line" is a string I read off a file that looks like "1 2 3 4 5").

Arrays.stream(line.split(" ")).map(Integer::valueOf).collect(toList()).toArray()

I hope you can help me understand, thank you !

1 Answer 1

2

The stream is of type Object, use mapToInt to convert as int:

Arrays.stream(line.split(" ")).mapToInt(Integer::parseInt).toArray()
Sign up to request clarification or add additional context in comments.

2 Comments

Pattern.compile(" ").splitAsStream(line).mapToInt(... avoids the temporary array, fwiw.
@Shawn but this only pays of for a rather large number of substrings, as otherwise, String.split is significantly faster than the regex engine when the pattern consists of a single ordinary character.

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.