2

I have set up the following ArrayList:

ArrayList<Integer> myIntegerValues = new ArrayList<Integer>();
myIntegerValues.add(0);
myIntegerValues.add(1);
myIntegerValues.add(0);
myIntegerValues.add(1);

I want to convert this to a double[] and run a simple piece of code like this

double[] myList = {1.9, 2.9, 3.4, 3.5, 2.9, 3.8, 10.2};        
for (int i = 0; i < myList.length; i++) {
    System.out.println(myList[i] + " ");
}

How do I convert an ArrayList to a double[]?

I found this link How to cast from List<Double> to double[] in Java? but I'm not sure if this answers my question or not.

Community
  • 1
  • 1
Mr.NoName
  • 125
  • 4
  • 13
  • Do you want 1 to be converted as 1.9 or 1.3 or something like that? How does anyone know what 1 in real value is unless you feed it out? You can though convert it from 1 to 1.0 – SSC Oct 06 '16 at 21:32
  • Did you have a look to this: http://stackoverflow.com/questions/718554/how-to-convert-an-arraylist-containing-integers-to-primitive-int-array ? Try to add a cast – acornagl Oct 06 '16 at 21:34
  • The java statistical package I am using requires `double[]` as an input. The ArrayList doesn't work as an input. So I am trying to convert the numbers in my ArrayList so that I can use them in the statistical package datastructures. – Mr.NoName Oct 06 '16 at 21:34
  • Best thing to do is to create an array of matching size and then iterate over the entries, casting as you go. – Andre M Oct 06 '16 at 21:35

3 Answers3

5
double[] array = myIntegerValues.stream().mapToDouble(i -> (double) i).toArray();
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

Declare a double arry of the size of the arraylist first, since arrays aren't dynamic.

double[] doublesList = new double[myIntegerValues.size()];

then loop through and convert each one

int x = 0;
for(Integer i : myIntegerValues){
    doublesList[x] = (double)i;
    x++;
}
SpacePrez
  • 1,086
  • 7
  • 15
0

Best thing to do is to create an array of matching size and then iterate over the entries, casting as you go.

double[] myList = new double[myIntegerValues.size()];
for (int i=0; i<myIntegerValues.size(); i++) {
   myList[i] = (double) myIntegerValues.get(i);
}

Note, while I could use an iterator, using indexes makes the one to one relationship clear.

Andre M
  • 6,649
  • 7
  • 52
  • 93