user2434222
user2434222

Reputation:

How to Access Elements in a List that is Contained in a Map?

I am attempting to access some elements stored in a list that is contained in a map. The keys in the map are doubles. The list I am attempting to access contains both a double and a map. The code below is my attempt to get a double stored in the list, as well as accessing a map contained in the list. There are 3 errors in the code below that I do not know how to solve. Any help would be great thanks.

private Map<Double,List<Object>> prediction = new HashMap<Double,List<Object>>();

// previous is a double that the user inputs

if(prediction.containsKey(previous)){
        List<Object> l1 = new ArrayList<>();
        l1.add(0,(double)l1.get(0)+1.0); // add double 1 at index 0
        Map<Double,Double> m2 = new HashMap<Double,Double>();
        l1.add(m2); // add map to list at index 1
        prediction.put(previous,l1);
}
public double predict(double value){ 

    if (prediction.containsKey(value)){
        double total = prediction.get(value).get(0); //ERROR can't convert Object to double
        Map items = prediction.get(value).get(1); //ERROR can't convert Object to Map           
        for (double i=0; i<=items.size();i++){ //iterate through Map
            double a = items.get(i)/total; //ERROR can't divide object by double
                    }
            }
}

Upvotes: 0

Views: 106

Answers (2)

eternay
eternay

Reputation: 3814

prediction.get(value) returns a List<Object>. So prediction.get(value).get(0) returns an Object: you need to cast it to Double and extract the double value:

double total = ((Double)prediction.get(value).get(0)).doubleValue();

Same with the second one: You have to cast to Map:

Map items = (Map)prediction.get(value).get(1);

And the same for the 3rd one:

double a = ((Double)items.get(i)).doubleValue()/total; 

Upvotes: 1

Georg Leber
Georg Leber

Reputation: 3580

Untested, but I think you can cast the values:

if (prediction.containsKey(value)){
    double total = (Double) prediction.get(value).get(0);
    Map items = (Map) prediction.get(value).get(1);
    for (double i=0; i<=items.size();i++) {
       double a = ((Double) items.get(i)) / total; 
    }
}

But this is not very clean code style. Try to split the Map into two maps. One containing Double and one containing Maps

Upvotes: 0

Related Questions