40

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;
}
Yasin Bahtiyar
  • 2,357
  • 3
  • 18
  • 18

4 Answers4

65

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[]
robinst
  • 30,027
  • 10
  • 102
  • 108
34

Google Guava : Longs.toArray(Collection)

long[] result = Longs.toArray(values);
cahen
  • 15,807
  • 13
  • 47
  • 78
lschin
  • 6,745
  • 2
  • 38
  • 52
17

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

Long[] l = values.toArray(new Long[values.size()]);
long[] l = ArrayUtils.toPrimitive(l);
Obicere
  • 2,999
  • 3
  • 20
  • 31
melhosseiny
  • 9,992
  • 6
  • 31
  • 48
1

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