How to convert Integer[] to int[] array in Java?

Michael picture Michael · Jul 14, 2015 · Viewed 31.2k times · Source

Is there a fancy way to cast an Integer array to an int array? (I don't want to iterate over each element; I'm looking for an elegant and quick way to write it)

The other way around I'm using

scaleTests.add(Arrays.stream(data).boxed().toArray(Double[]::new));

I'm looking for an one-liner but wasn't able to find something.

The goal is to:

int[] valuesPrimitives = <somehow cast> Integer[] valuesWrapper

Answer

Vaibhav picture Vaibhav · Jul 14, 2015

You can use Stream APIs of Java 8

int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();