3

I want to convert a string to an Integer Array. So basically i have a string of integers separated by spaces such as: "10 2 3 100" I am trying to convert this to an Integer Array. All the answers I've searched for converts it to an int array. Of course, I can convert this to a int array, then turn the int array to an Integer array.

int[] numbers = Arrays.stream(string.split(" ")).mapToInt(Integer::parseInt).toArray(); 
//then a method to turn this into an Integer[]

Can you guys tell me if there is a shorter way to do this? (Like in one line) Thanks!

1 Answer 1

4

Rather than IntStream, you still want the Stream type (Stream<Integer> specifically), so instead of mapToInt, you should call map. Then to convert the resulting Stream<Integer> to an array, call toArray(Integer[]::new):

Arrays.stream(string.split(" "))
    .map(Integer::parseInt)
    .toArray(Integer[]::new);
Sign up to request clarification or add additional context in comments.

Comments

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.