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

Solution 1:

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.

Solution 2:

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.