Convert String to Integer(Object) Array Java

Viewed 271

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 Answers

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