Since Java 8, you can do the following:
long[] result = values.stream().mapToLong(l -> l).toArray();
What’s happening here?
- We convert the
List<Long>into aStream<Long>. - We call
mapToLongon it to get aLongStream- The argument to
mapToLongis aToLongFunction, which has alongas the result type. - Because Java automatically unboxes a
Longto along, writingl -> las the lambda expression works. TheLongis converted to alongthere. We could also be more explicit and useLong::longValueinstead.
- The argument to
- We call
toArray, which returns along[]