Converting an array of objects to an array of their primitive types Converting an array of objects to an array of their primitive types arrays arrays

Converting an array of objects to an array of their primitive types


Once again, Apache Commons Lang is your friend. They provide ArrayUtils.toPrimitive() which does exactly what you need. You can specify how you want to handle nulls.


With streams introduced in Java 8 this can be done:

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

However, there are currently only primitive streams for int, long and double. If you need to convert to another primitive type such as byte the shortest way without an external library is this:

byte[] byteArray = new byte[array.length];for(int i = 0; i < array.length; i++) byteArray[i] = array[i];

Or the for loop can be replaced with a stream if you want:

IntStream.range(0, array.length).forEach(i -> byteArray[i] = array[i]);

All of these will throw a NullPointerException if any of your elements are null.


Unfortunately, there's nothing in the Java platform that does this. Btw, you also need to explicitly handle null elements in the Integer[] array (what int are you going to use for those?).