我有一个变量:
List<Double> frameList = new ArrayList<Double>();
/* Double elements has added to frameList */
在Java中,我如何高效地将一个变量转换为类型为double[]
的新变量?
使用 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()
以获取数组。性能高 - 每个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)
顺便说一下,Marcelo的答案的复杂度为O(2n),因为它会迭代两次(在幕后):首先从列表中创建Double[]
,然后再展开double
值。
doubles.get(i)
,尽管我们知道提问者提供了一个ArrayList。像这样的方法:double[] tmp = new double[doubles.size()];
int idx = 0;
for (Double d : doubles) {
tmp[idx] = d;
idx++;
}
适用于每个List(甚至Collection)。 - user3389669Guava提供了一个方法来为您完成此操作:double[] Doubles.toArray(Collection<Double>)
这不一定比只循环遍历Collection
并将每个Double
对象添加到数组中更快,但是它让您需要编写的代码量少得多。
List<Double> frameList = new ArrayList<Double>();
First you have to convert List<Double>
to Double[]
by using
Double[] array = frameList.toArray(new Double[frameList.size()]);
Next you can convert Double[]
to double[]
using
double[] doubleArray = ArrayUtils.toPrimitive(array);
double[] array = ArrayUtils.toPrimitive(frameList.toArray(new Double[frameList.size()]));
ArrayUtils
是Apache库的一部分,不属于标准Java库:org.apache.commons.lang3.ArrayUtils
。但无论如何使用它都是一个很好的解决方案。 - brimborium你可以使用commons-lang中的ArrayUtils
类从Double[]
获取double[]
。
Double[] ds = frameList.toArray(new Double[frameList.size()]);
...
double[] d = ArrayUtils.toPrimitive(ds);
你可以通过调用frameList.toArray(new Double[frameList.size()])
将其转换为Double[]
,但是需要迭代列表/数组来转换为double[]
您可以使用来自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();
map
返回一个惰性流,请参见https://dev59.com/O2Ag5IYBdhLWcg3wWp3-#23696571)。 - Alexis C.