我有一个像这样的变量:
List<Double> frameList = new ArrayList<Double>();
/* Double elements has added to frameList */
如何让Java中的变量具有double[]
类型的新变量具有高性能?
答案 0 :(得分:80)
使用java-8,您可以这样做。
double[] arr = frameList.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference
double[] arr = frameList.stream().mapToDouble(d -> d).toArray(); //identity function, Java unboxes automatically to get the double value
它的作用是:
Stream<Double>
DoubleStream
toArray()
以获取阵列。答案 1 :(得分:40)
高性能 - 每个Double
对象包含一个double
值。如果要将所有这些值存储到double[]
数组中,那么有来遍历Double
个实例的集合。无法进行O(1)
映射,这应该是您获得的最快速度:
double[] target = new double[doubles.size()];
for (int i = 0; i < target.length; i++) {
target[i] = doubles.get(i).doubleValue(); // java 1.4 style
// or:
target[i] = doubles.get(i); // java 1.5+ style (outboxing)
}
感谢评论中的其他问题;)以下是拟合ArrayUtils#toPrimitive
方法的源代码:
public static double[] toPrimitive(Double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_DOUBLE_ARRAY;
}
final double[] result = new double[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].doubleValue();
}
return result;
}
(相信我,我没有用它作为我的第一个答案 - 即使它看起来......很相似:-D)
顺便说一下,Marcelos答案的复杂性是O(2n),因为它迭代两次(幕后):首先从列表中创建Double[]
,然后打开double
值。
答案 2 :(得分:25)
Guava有一种为您执行此操作的方法:double[] Doubles.toArray(Collection<Double>)
这不一定比通过Collection
循环并将每个Double
对象添加到数组更快,但是你编写的内容要少得多。
答案 3 :(得分:6)
您可以使用commons-lang中的ArrayUtils
类从double[]
获取Double[]
。
Double[] ds = frameList.toArray(new Double[frameList.size()]);
...
double[] d = ArrayUtils.toPrimitive(ds);
答案 4 :(得分:5)
您可以通过调用Double[]
转换为frameList.toArray(new Double[frameList.size()])
,但您需要迭代列表/数组以转换为double[]
答案 5 :(得分:4)
根据你的问题,
List<Double> frameList = new ArrayList<Double>();
首先,您必须使用
将List<Double>
转换为Double[]
Double[] array = frameList.toArray(new Double[frameList.size()]);
接下来,您可以使用
将Double[]
转换为double[]
double[] doubleArray = ArrayUtils.toPrimitive(array);
您可以直接在一行中使用它:
double[] array = ArrayUtils.toPrimitive(frameList.toArray(new Double[frameList.size()]));
答案 6 :(得分:2)
您可以使用Eclipse Collections中的原始集合并完全避免装箱。
DoubleList frameList = DoubleLists.mutable.empty();
double[] arr = frameList.toArray();
如果您不能或不想初始化DoubleList
:
List<Double> frames = new ArrayList<>();
double[] arr = ListAdapter.adapt(frames).asLazy().collectDouble(each -> each).toArray();
注意:我是Eclipse Collections的撰稿人。