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?
- 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[]
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();
}
}
}
}
精彩评论