-1

How to Convert ArrayList to Double Array in Java6?

 List lst = new ArrayList();
 double[] dbl=null;
 lst.add(343.34);
 lst.add(432.34);

How convert above list to array?

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
Ram
  • 9
  • 1
  • 1
  • 3
  • Have you tried something ? Have you search ? This is a common question that you can find a lot of answer. Also, please add a type to the `List` like `List` ... it will be messy if you don't – AxelH Nov 16 '17 at 07:52
  • @TrầnAnhNam Not really a duplicate. In that post the ArrayList contains String objects, here it contains Double objects. – Bernhard Barker Nov 16 '17 at 09:14
  • Duplicate of [How to cast from List to double\[\] in Java?](https://stackoverflow.com/q/6018267) – Bernhard Barker Nov 16 '17 at 09:15
  • Your code doesn't match your question. A Double Array (`Double[]`) is not a double array (`double[]`) - those are different types. Which one are you trying to convert to? – Bernhard Barker Nov 16 '17 at 09:28
  • Before you post code her asking other people to help you, check that your code compiles without error or warning massages. – Raedwald Nov 16 '17 at 17:04

3 Answers3

2

You can directly convert the List to an Array of the wrapper class. Try the following:

List<Double> lst = new ArrayList<>();
Double[] dblArray = new Double[lst.size()];
lst.add(343.34);
lst.add(432.34);
dblArray = lst.toArray(dblArray);
Yash
  • 11,486
  • 4
  • 19
  • 35
  • 1
    no need of specifying size. just `dblArray =lst.toArray(new Double[0])` – Nonika Nov 16 '17 at 07:59
  • 1
    @Nonika if you do not specify the size (or the size isn't correct), a new array will be created automatically. This does not usually matter, but it's still a significant difference in that your code will create 2 arrays, whereas the code in the answer only creates one. – Kayaman Nov 16 '17 at 09:03
0
List<Number> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42);
double[] dbl = lst.stream()
    .map(Number::cast) // Or possibly Double::cast when List lst.
    .mapToDouble(Number::doubleValue)
    .toArray();

List<Double> lst = new ArrayList<>();
Collections.addAll(lst, 3.14, -42.0);
double[] dbl = lst.stream()
    .mapToDouble(Double::doubleValue)
    .toArray();

The mapToDouble transforms an Object holding Stream to a DoubleStream of primitive doubles.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
-1

With this you will make the list and add what you like. Then make the array the same size and fill front to back.

public static void main(String[] args){
        List lst = new ArrayList();
        lst.add(343.34);
        lst.add(432.34);
        System.out.println("LST " + lst);

        double[] dbl= new double[lst.size()];
        int iter = 0;
        for (Object d: lst
             ) {
            double e = (double) d;
            dbl[iter++] = e;
        }
        System.out.println("DBL " + Arrays.toString(dbl));
    }

Result: LST [343.34,432.34] DBL [343.34,432.34]

G2M
  • 68
  • 1
  • 6