转换List< Long>的最佳方法是什么?对象到java中的long []数组? [英] What is the best way of converting List<Long> object to long[] array in java?

查看:101
本文介绍了转换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();

这里发生了什么?


  1. 我们将列表< Long> 转换为流< Long>

  2. 我们致电 mapToLong 就可以获得 LongStream


    • mapToLong 的参数是 ToLongFunction ,其长度 作为结果类型。

    • 因为Java自动将 Long 解包为,写 l - > l ,因为lambda表达式有效。 Long 在那里转换为 long 。我们也可以更明确地使用 Long :: longValue

  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.

这篇关于转换List&lt; Long&gt;的最佳方法是什么?对象到java中的long []数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆