开发者

What is the best way of converting List<Long> object to long[] array in java?

Is there any utility method to convert a list of Numerical types to array of primitive type? In other words I am looking for a better solution than开发者_运维技巧 this.

private long[] toArray(List<Long> values) {
    long[] result = new long[values.size()];
    int i = 0;
    for (Long l : values)
        result[i++] = l;
    return result;
}


Since Java 8, you can do the following:

long[] result = values.stream().mapToLong(l -> l).toArray();

What's happening here?

  1. We convert the List<Long> into a Stream<Long>.
  2. We call mapToLong on it to get a LongStream
    • The argument to mapToLong is a ToLongFunction, which has a long as the result type.
    • Because Java automatically unboxes a Long to a long, writing l -> l as the lambda expression works. The Long is converted to a long there. We could also be more explicit and use Long::longValue instead.
  3. We call toArray, which returns a long[]


Google Guava : Longs.toArray(Collection)

long[] result = Longs.toArray(values);


Use ArrayUtils.toPrimitive(Long[] array) from Apache Commons.

Long[] l = values.toArray(new Long[values.size()]);
long[] l = ArrayUtils.toPrimitive(l);


I don't recall about some native method that will do that but what is wrong with creating a self one ;-).

public class YasinUtilities {

    public static long[] toArray(Iterator<Long) values) { //Better choice would be Enumerator but easier is this way. 

      if(value == null) {
        //return null or throw exception 
      }

      long[] result = new long[values.size()];

      Long current = null;
      int i = 0;
      while(values.hasNext()) {

       current = values.next();

       if(current == null) {
         result[i++] = 0L; //or -1;
       } else {
         result[i++] = current.longValue();
       }
      }
   } 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜