【问题标题】:How to add all values in a HashMap?如何在 HashMap 中添加所有值?
【发布时间】:2019-05-15 21:50:52
【问题描述】:

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

这是我的HashMap 的sn-p,用于商店的商品和价格:

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 非常陌生,并且对如何将股票地图引用到价格方法中并正确添加它感到非常困惑。理论上,这个问题的最终答案是 2 个鸡蛋和 2 个橙汁盒的价格。非常感谢帮助

【问题讨论】:

标签: java hashmap


【解决方案1】:

上面的人已经为您提供了代码 sn-ps,但我将根据 Chris Bertasi 的回答更详细地介绍发生了什么,因为它最容易阅读,因为您是 Hashmaps 的新手。

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

这个sn-p所做的就是创建一个Hashmap,你可以把它想象成类似于有两列的关系数据库。其中列是键和值。

我们附加的第一件事 ("eggs") 是我们用来查找附加内容的密钥 (1.79),然后对 OJ 也是如此。生成的 Hashmap 看起来像这样。

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

所以要得到鸡蛋的价格,你可以简单地使用stock.get("egg")询问Hashmap,它会返回值1.79

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

因此,一旦我们将商品添加到购物车中,我们希望遍历它并获得总成本。

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

for (String item: cart.keySet())

这是做什么的,它将通过 Key Set(即 Key Column)进行查看,并一次获得一个 Key 并将其设置为项目变量。

利用这些知识,我们可以通过库存和购物车来获取每件商品的价格和用户购买的数量。

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

使用此信息,我们可以通过以下方式生成总成本:

totalCost += amount * price;

将这些拼凑在一起得到了这个 sn-p,我们在其中迭代每个关键元素并通过 .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】:

    遍历购物车条目,转换为行项目价格,然后求和。

    您可以为此使用流:

    double total = cart.entrySet().stream()
        .mapToDouble(entry -> entry.getValue() * stock.get(entry.getKey()))
        .sum();
    

    【讨论】:

      【解决方案3】:

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

      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】:

        试试这个

        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;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-04
          • 1970-01-01
          • 2023-04-09
          相关资源
          最近更新 更多