java - 嵌套HashMap值乘法-Java
问题描述
从下面的代码中可以得到apple 1.50 pears 6
如果不是,那么至少 1.50 和 6?我已经做了一些事情来实现这一点/阅读了一些堆栈溢出但现在确定如何做到这一点。提前感谢您的时间/评论。强调文本
public class RandomCheck {
public static void main(String[] args) {
//Keep Track of Fruit, Quantity and Price per item
Map<String, Map<Integer, Double>> mapOuter = new HashMap<String, Map<Integer, Double>>();
//Keep Track of Quantity and Price per item
Map<Integer, Double> mapInner = new HashMap<Integer, Double>();
mapInner.put(2, .75);
mapInner.put(4, 1.25);
mapOuter.put("apple", mapInner);
mapOuter.put("pears", mapInner);
//ToDo: Get Final price of this purchase all together will be (2*.$75) + (4* $1.25)= $6.5
double finalTotal = 0;
for (Map.Entry<Integer, Double> innerData : mapInner.entrySet()) {
finalTotal = finalTotal + (innerData.getKey() * innerData.getValue());
}
System.out.println("Total price " + finalTotal);
//ToDo:Get itemized total, for Apple it will be 2* $.75 and for pears 4* $1.25
double totalByItem = 0;
/* for (Map.Entry<String, Map<Integer, Double>> outerData : mapOuter.entrySet()) {
for (Map.Entry<Integer, Double> innerData : mapInner.entrySet()) {
// System.out.println(" KEY Outer "+ outerData.getKey() + " KEY Inner " + innerData.getKey() + " Value Inner " + innerData.getValue());
totalByItem = totalByItem + (innerData.getKey() * innerData.getValue());
}
}
System.out.println("By item price " + totalByItem);*/
/* Iterator <k> itr= map.keySet().iteraotr;
while(itr.hasNext()){
K key = its.next();
V value= map.get(key);
}*/
}
}
解决方案
您的地图不应该是这样的结构:
Map<String, Integer> quantity = new HashMap<>();
quantity.put("apple", 2);
quantity.put("pears", 4);
Map<String, Double> price = new HashMap<>();
price.put("apple", .75);
price.put("pears", 1.25);
然后您可以执行以下操作:
for(String fruit : quantity.keySet())
{
int fruitQuantity = quantity.get(fruit);
double fruitPrice = price.get(fruit);
// ...
}
顺便说一句,梨的总数应该是 5 而不是 6。
推荐阅读
- flutter - 如何在 Flutter 中突出显示特定字母的文本?
- django - 访问 XMLHttpRequest 在。从原产地。已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头
- python - Python每组插入连续数字
- swift - SwiftUI macOS Xcode 样式工具栏
- reactjs - 想要在 redux 中的状态更改时重新渲染表行
- angular - FormArray 和 formGroup 中的 Angular Material mat-select
- javascript - Video-React:handleStateChange 被多次调用,而它应该只被调用一次
- reactjs - 如何使用外部 css 在 Reactjs 中设置背景图像?
- xamarin - 我应该在创建 Xamarin 对象的类的签名中使用 BindingBase 而不是 Binding 吗?
- android - channel 或 mutablesharedflow ,哪个是已弃用的 localbroadcastmanager 的更好替代品