I have a nested map:
Map<Integer, Map<Integer, Double>> areaPrices = new HashMap<Integer, Map<Integer, Double>>();
and this map is populated using the code:
while(oResult.next())
{
Integer areaCode = new Integer(oResult.getString("AREA_CODE"));
Map<Integer, Double> zonePrices = areaPrices.get(areaCode);
if(zonePrices==null)
{
zonePrices = new HashMap<Integer, Double>();
areaPrices.put(areaCode, zonePrices);
}
Integer zoneCode = new Integer(oResult.getString("ZONE_CODE"));
Double value = new Double(oResult.getString("ZONE_VALUE"));
zonePrices.put(zoneCode, value);
myBean.setZoneValues(areaPrices);
}
I want to use the value of this Map in another method of the same class. For that I have a bean.
How do I populate it on the bean, so that I can get the ZONE_VALUE in this other method
In my bean I added one new field as:
private Map<Integer, Map<Integer, Double>> zoneValues;
with getter and setter as:
public Map<Integer, Map<Integer, Double>> getZoneValues() {
return zoneValues;
}
public void setZoneValues(Map<Integer, Map<Integer, Double>> areaPrices) {
this.zoneValues = areaPrices;
}
What I am looking for to do in the other method is something like this:
Double value = myBean.get(areaCode).get(zoneCode);
How do I make it happen 🙁
You can’t directly control the second get() call because you have a nested Map, you’ll need to return the appropriate nested Map to be able to do what you want. A getter like this should do it:
So when the client code calls
get(areaCode)a map will be returned that they can then callget(zoneCode)on.I’d suggest that you refactor to eliminate the nested Maps though, because you can’t stop client code from changing the returned Map, the code is tough to read and you’ll have problems if you want to add any more functionality – imagine that you want to provide a String description of an area code in future.
Something like a
Map<Integer, AreaCode>whereAreaCodeis an object that contains what you currently have as a nested Map might be a good place to start.