代码之家  ›  专栏  ›  技术社区  ›  J.Doe

如何在HashMap中添加所有值?

  •  1
  • J.Doe  · 技术社区  · 7 年前

    我有一个任务,我必须制作一个包含价格的杂货库存哈希图。然后,我必须制定一种方法,其中存在一辆装有这些物品的购物车,我必须找到总价。

    这是我的 HashMap 对于有商品和价格的商店:

    HashMap<String, Double>stock= new HashMap<String, Double>(); 
    stock.put("eggs",1.79);
    stock.put("orange juice",2.5); 
    
    
    public static double price(HashMap<String, Double>stock){
    
        HashMap<String, Integer>cart = new HashMap<String, Integer>();
        cart.put("eggs", 2);
        cart.put("orange juice", 2);
    }
    

    这是我的购物车,其中int表示购物车中每种商品的数量。我对HashMaps非常陌生,对于如何将股票映射引用到price方法中并正确地将其相加,我感到非常困惑。理论上,最终的答案是2个鸡蛋和2盒橙汁的价格。非常感谢您的帮助

    4 回复  |  直到 6 年前
        1
  •  1
  •   A.A    7 年前

    上面的人给了你一些代码片段,但我将根据Chris Bertasi的回答更详细地介绍一下发生了什么,因为这是最容易阅读的,因为你是Hashmaps新手。

    HashMap<String, Double>stock= new HashMap<String, Double>(); 
    stock.put("eggs",1.79);
    stock.put("orange juice",2.5); 
    

    这个代码段所做的是创建一个Hashmap,您可以认为它类似于具有两列的关系数据库。其中列是键和值。

    我们附加的第一件事( "eggs" )是我们用来查找附件的钥匙( 1.79 )OJ也一样。生成的Hashmap如下所示。

    Item (Key)    | Price (Value)
    ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
    egg           | 1.79
    orange juice | 2.5
    

    因此,要获得鸡蛋的价格,只需使用 stock.get("egg") 它将返回值 1.79 返回

    同样的逻辑也适用于购物车,它是数量金额而不是价格(例如,返回的是2而不是1.79)。

    因此,一旦我们将这些项目添加到购物车中,我们就要遍历它并获得总成本。

    要迭代我们的库存,我们可以使用:

    for (String item: cart.keySet())
    

    它将查看键集(即键列),每次获取一个键,并将其设置为项变量。

    利用这些知识,我们可以浏览股票和;cart获取每个项目的价格和用户购买的金额。

    double amount = cart.get(item); 
    double price = stock.get(item); 
    

    利用这些信息,我们可以通过以下方式生成总成本:

    totalCost += amount * price;
    

    将其拼凑在一起,我们将得到这个片段,在这里我们遍历每个关键元素,并通过 .get() 方法

    double totalCost = 0;
    for (String item: cart.keySet()) {
        double amount = cart.get(item);
        double price = stock.get(item);
        totalCost += amount * price; 
    }
    return totalCost;
    
        2
  •  1
  •   Bohemian    7 年前

    循环遍历购物车条目,转换为商品价格,然后求和。

    您可以为此使用流:

    double total = cart.entrySet().stream()
        .mapToDouble(entry -> entry.getValue() * stock.get(entry.getKey()))
        .sum();
    
        3
  •  0
  •   Jayanth    7 年前

    由于您是初学者,这段代码可能会有所帮助。这是一种精细/详细的做事方式:

    import java.util.HashMap;
    import java.util.Iterator;
    
    
    public class Grocery {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
             HashMap<String, Double>stock= new HashMap<String, Double>(); 
                stock.put("eggs",1.79);
                stock.put("orange juice",2.5); 
    
                HashMap<String, Integer>cart = new HashMap<String, Integer>();
                cart.put("eggs", 2);
                cart.put("orange juice", 2);
                System.out.println(price(stock,cart));//prints the total cart value/price
    
        }
                public static double price(HashMap<String, Double>stock,HashMap<String, Integer>cart){
    
                  Iterator<String> productItr = cart.keySet().iterator();//get each product in the cart
                  double price=0;
                  while(productItr.hasNext()){
                      String product =productItr.next();
                      price=price+( cart.get(product)*stock.get(product));
                  }
    
    
                    return price;
            }
    
    }
    
        4
  •  0
  •   Gowthaman M manas.abrol    7 年前

    试试这个

    public static double price(HashMap<String, Double> stock){
    
    
        HashMap<String, Integer> cart = new HashMap<String, Integer>();
        cart.put("eggs", 2);
        cart.put("orange juice", 2);
        // the cart hashmap now contains all the items in our shopping cart
    
        // we want to get the prices of all items in our cart, and multiple by the amount we are purchasing
        double cost = 0;
        for (String item: cart.keySet()) { // for every item we are purchasing
            double amount = cart.get(item); // how much we are purchasing
            double price = stock.get(item); // how much it costs
            cost += amount * price; // update the total price
        }
        return cost;
    }