-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?

5
  • 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<Double> ... it will be messy if you don't
    – AxelH
    Commented Nov 16, 2017 at 7:52
  • @TrầnAnhNam Not really a duplicate. In that post the ArrayList contains String objects, here it contains Double objects. Commented Nov 16, 2017 at 9:14
  • Duplicate of How to cast from List to double[] in Java? Commented Nov 16, 2017 at 9: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? Commented Nov 16, 2017 at 9:28
  • Before you post code her asking other people to help you, check that your code compiles without error or warning massages.
    – Raedwald
    Commented Nov 16, 2017 at 17:04

3 Answers 3

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);
2
  • 1
    no need of specifying size. just dblArray =lst.toArray(new Double[0])
    – Nonika
    Commented Nov 16, 2017 at 7: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
    Commented Nov 16, 2017 at 9: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.

-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]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.