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
mapToLong
on it to get aLongStream
- The argument to
mapToLong
is aToLongFunction
, which has along
as the result type. - Because Java automatically unboxes a
Long
to along
, writingl -> l
as the lambda expression works. TheLong
is converted to along
there. We could also be more explicit and useLong::longValue
instead.
- The argument to
- We call
toArray
, which returns along[]