Converting an array of objects to an array of their primitive types
Solution 1
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?).
Solution 2
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 3
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
.
Solution 4
Using Guava:
int[] intArray = Ints.toArray(Arrays.asList(array));
Documentation:
-
Arrays.asList
(Core API) -
Ints.toArray
(Guava)
Solution 5
In particular can this be done without having to create a new array and loop through the contents.
You can't convert an array of Integer to int (i.e. you can't change the type of the elements of an array) in Java. So you either must create a new int[] array and copy the value of the Integer objects into it or you can use an adapter:
class IntAdapter {
private Integer[] array;
public IntAdapter (Integer[] array) { this.array = array; }
public int get (int index) { return array[index].intValue(); }
}
This can make your code a little more readable and the IntAdapter object will only consume a few bytes of memory. The big advantage of an adapter is that you can handle special cases here:
class IntAdapter {
private Integer[] array;
public int nullValue = 0;
public IntAdapter (Integer[] array) { this.array = array; }
public int get (int index) {
return array[index] == null ? nullValue : array[index].intValue();
}
}
Another solution is to use Commons Primitives which contains lots of predefined adapters. In your case, have a look at ListIntList.
Related videos on Youtube
Il-Bhima
Updated on July 05, 2022Comments
-
Il-Bhima almost 2 years
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!
-
Il-Bhima about 15 yearsGood point about the nulls. For my purposes I would have accepted an exception being thrown if one of the entries is null, the same way an NullPointerException is thrown when you unbox an object.
-
Lordalcol almost 11 yearsThis does not appear to be Java, at least not Java 1.6 or 1.7.
-
Jaroslav Záruba over 9 years@LorDalCol Dollar is actually a Java library
-
robinst almost 9 yearsThis answer is no longer accurate with Java 8, see Alex's answer.
-
robinst almost 9 yearsInstead of
Integer::intValue
, you can also usei -> i
(which uses unboxing). -
Andreas about 8 years@robinst And unboxing is the compiler calling
Integer::intValue
for you, so why create a new lambda, when the method is readily available? -
robinst about 8 years@Andreas Just listing another option, which one you choose is a question of code style/personal preference. I also microbenchmarked (using JMH) the two approaches, and they have the same performance.
-
Kartik Chugh almost 5 yearsUsing the first code snippet posted was giving me a "Can't use non-static method in static context" error so I instead did:
int[] ints = Arrays.stream(objects).mapToInt(i -> Integer.parseInt(i.toString())).toArray();
Hope this is helpful for anyone with the same issue. And if anyone knows a better way please let me know. -
Ole V.V. over 4 yearsIt is possible to name a Java method
$
! I don’t think it’s encouraged, though… -
Per Lundberg about 4 yearsThis should be the accepted answer nowadays. Thanks Alex.
-
Björn Zurmaar over 2 years
Arrays.setAll(unboxed, i -> boxed[i]);
is a nice alternative to the for loop from my perspective. -
Alex - GlassEditor.com over 2 years@BjörnZurmaar
setAll
only has overloads for the same primitive types as streams, so you couldn't use it forbyte
, but you could doArrays.setAll(array, i -> byteArray[i] = array[i])
which will also write to the original array.