簡體   English   中英

如何在Java中從List <Double>轉換為double []?

[英]How to cast from List<Double> to double[] in Java?

我有一個這樣的變量:

List<Double> frameList =  new ArrayList<Double>();

/* Double elements has added to frameList */

如何在Java中使用具有高性能的變量的新變量具有double[]類型?

使用 ,您可以這樣做。

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>
  • 將每個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)

順便說一句,Marcelos答案的復雜性是O(2n),因為它迭代了兩次(幕后):首先從列表中創建一個Double[] ,然后打開double值。

番石榴有一種方法可以為你做到這一點: double [] Doubles.toArray(Collection <Double>)

這不一定比通過循環遍歷Collection並將每個Double對象添加到數組更快,但是你寫的要少得多。

您可以使用commons-lang中的ArrayUtils類從Double[]獲取double[] Double[]

Double[] ds = frameList.toArray(new Double[frameList.size()]);
...
double[] d = ArrayUtils.toPrimitive(ds);

根據你的問題,

List<Double> frameList =  new ArrayList<Double>();
  1. 首先,您必須使用將List<Double>轉換為Double[]

     Double[] array = frameList.toArray(new Double[frameList.size()]); 
  2. 接下來,您可以使用Double[]轉換為double[]

     double[] doubleArray = ArrayUtils.toPrimitive(array); 

您可以直接在一行中使用它:

double[] array = ArrayUtils.toPrimitive(frameList.toArray(new Double[frameList.size()]));

您可以通過調用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();

注意:我是Eclipse Collections的貢獻者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM