How do i convert Long[] to long[]? For example i know how to convert if it is not array as below.
long ll = (Long)Object[1].longValue()
But how
You could steal a solution based on ArrayUtils
Long[] longObjects = { 1L, 2L, 3L };
long[] longArray = ArrayUtils.toPrimitive(longObjects);
There are no standard API method for doing that (how would null
-elements be handled?) so you would need to create such a method yourself.
Something like this (will throw NullPointerException
on any object beeing null
):
public static long[] toPrimitives(Long... objects) {
long[] primitives = new long[objects.length];
for (int i = 0; i < objects.length; i++)
primitives[i] = objects[i];
return primitives;
}
In order to do this, the best way would be to navigate through each array.
For instance, going from Long[] to long[]:
Long[] objLong = new Long[10];
//fill objLong with some values
long[] primLong = new long[objLong.length]
for(int index = 0; index < objLong.length; index++)
{
primLong[index] = objLong[index];
}
Due to auto-unboxing, this should work out by converting Long to long.
using java 8 streams:
public static long[] unboxed(final Long[] array) {
return Arrays.stream(array)
.filter(Objects::nonNull)
.mapToLong(Long::longValue)
.toArray();
}
Thanks for everyone's answer; I am just pasting my final chosen solution.
List<Long> longObjects = new ArrayList<Long>();
long[] longArray2 = ArrayUtils.toPrimitive(longObjects.toArray(new Long[longObjects.size()]));