how to store LinkedHashMap value into double type array

521 views Asked by At

I want to store LinkedHashMap value into double type array. How to do that ?

I tried in this way

 Double[] avg=  (Double[]) averageMap.values().toArray();

where averageMap is:

LinkedHashMap<String, Double> averageMap = new LinkedHashMap<String, Double>();

but I have the following exception :

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Double;
2

There are 2 answers

2
Nirav Prajapati On BEST ANSWER

Below code will work for you but its not good enough

        Object[] objArray = averageMap.values().toArray();
        double[] dblArray = new double[objArray.length];
        for (int i = 0; i < objArray.length; i++) {
            dblArray[i] = Double.parseDouble(objArray[i].toString());
        }

averageMap.values().toArray(); method returns object[] so you have to cast it to Double or pars it to double[]

but its not good practice to parse it to double.instead of double use Double class.it is wrapper class so autoboxing done automatically so no need to worry

0
Seelenvirtuose On

The toArray function might be a bit complicated. It returns an Object[] which cannot be cast to Double[]. You have to use this code snippet instead:

Collection<Double> values = averageMap.values();
Double[] avg = values.toArray(new Double[values.size()]);