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

后端 未结 5 712
感情败类
感情败类 2021-02-18 13:13

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

相关标签:
5条回答
  • 2021-02-18 13:18

    You could steal a solution based on ArrayUtils

    Long[] longObjects = { 1L, 2L, 3L };
    long[] longArray = ArrayUtils.toPrimitive(longObjects);
    
    0 讨论(0)
  • 2021-02-18 13:19

    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;
    }
    
    0 讨论(0)
  • 2021-02-18 13:24

    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.

    0 讨论(0)
  • 2021-02-18 13:25

    using java 8 streams:

    public static long[] unboxed(final Long[] array) {
        return Arrays.stream(array)
                     .filter(Objects::nonNull)
                     .mapToLong(Long::longValue)
                     .toArray();
    }
    
    0 讨论(0)
  • 2021-02-18 13:30

    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()]));
    
    0 讨论(0)
提交回复
热议问题