首页 > 解决方案 > 嵌套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);
        }*/
    }
}

标签: javahashmapnested

解决方案


您的地图不应该是这样的结构:

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。


推荐阅读