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?
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);
dblArray =lst.toArray(new Double[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.
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]
ListlikeList<Double>... it will be messy if you don'tDouble[]) is not a double array (double[]) - those are different types. Which one are you trying to convert to?