转换List< Long>的最佳方法是什么?对象到java中的long []数组? [英] What is the best way of converting List<Long> object to long[] array in java?
本文介绍了转换List< Long>的最佳方法是什么?对象到java中的long []数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有任何实用工具方法可以将数值类型列表转换为基本类型数组?
换句话说,我正在寻找比这更好的解决方案。
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;
}
推荐答案
从Java 8开始,你可以执行以下操作:
Since Java 8, you can do the following:
long[] result = values.stream().mapToLong(l -> l).toArray();
这里发生了什么?
- 我们将
列表< Long>
转换为流< Long>
。 - 我们致电
mapToLong
就可以获得LongStream
-
mapToLong
的参数是ToLongFunction
,其长度 - 因为Java自动将
Long
解包为长
,写l - > l
,因为lambda表达式有效。Long
在那里转换为long
。我们也可以更明确地使用Long :: longValue
。
-
- 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
这篇关于转换List< Long>的最佳方法是什么?对象到java中的long []数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文