Osman Khalid
Osman Khalid

Reputation: 798

Java Cast from Object[] to double[] array and Double[] to double[] array

Is there a way to cast an Object[] array into double[] array without using any loops. And cast Double[] array to double[] array

Upvotes: 1

Views: 1832

Answers (1)

tomrlh
tomrlh

Reputation: 1066

In 2013 we haven't Java Stream API, just in march of 2014. With it you can get your answer:

From Object[] to double[]

Object[] objectArray = {1.0, 2.0, 3.0};

double[] convertedArray = Arrays.stream(objectArray) // converts to a stream
    .mapToDouble(num -> Double.parseDouble(num.toString())) // change each value to Double
    .toArray(); // converts back to array

From Double[] to double[]

Double[] doubleArray = {1.0, 2.0, 3.0};

double[] conv = Arrays.stream(doubArray)
    .mapToDouble(num -> Double.parseDouble(num.toString()))
    .toArray();

You notice that it's the same operation, since the resulting type for both conversions are double[]. What is changed is the source data.

PS: what a late answer :|

Upvotes: 1

Related Questions