convert Long[] to long[] (primitive) java

using java 8 streams:

public static long[] unboxed(final Long[] array) {
    return Arrays.stream(array)
                 .filter(Objects::nonNull)
                 .mapToLong(Long::longValue)
                 .toArray();
}

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.


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;
}

Tags:

Java