If you have an array of Java objects which have a primitive type (for example Byte, Integer, Char, etc). Is there a neat way I can convert it into an array of the primitive type? In particular can this be done without having to create a new array and loop through the contents.
So for example, given
Integer[] array
what is the neatest way to convert this into
int[] intArray
Unfortunately, this is something we have to do quite frequently when interfacing between Hibernate and some third party libraries over which we have no control. It seems this would be a quite common operation so I would be surprised if there's no shortcut.
Thanks for your help!
Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is: Passed as a parameter to a method that expects an object of the corresponding wrapper class.
Unboxing is the process of automatically converting a wrapper type into its equivalent primitive type. It is the reversal of the autoboxing process.
Converting an array to Set object The Arrays class of the java. util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.
creating an array of integers int[] a = new int[5]; creating a reference to created array int[] b = a; adding integer to array "a", position 0. overwriting previously added integer, because b[0] is pointing to the same location as a[0]
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With