在 Java 中的哈希图中查找特定项目的数量



我有一个方法,我用它来计算哈希图中的项目:

public void getAvailable(final Item item) {
    System.out.println("n" + "Item's "" + item.getItemName() + "" stock");
    System.out.println("NametPricetAmount");
    for (Map.Entry<Item, Integer> entry : stockItems.entrySet()) {
        System.out.println(entry.getKey() + "t" + entry.getValue());
    }
}

但是,如果我指定了键item,如何在哈希图中找到具有该键的所有项目的数量?目前,它返回给我所有带有不同键的项目。

以下内容会达到您所追求的目标吗?

public int getAvailable(final Item item) {
    int count = 0;
    String itemName = item.getItemName();
    for (Map.Entry<Item, Integer> entry : stockItems.entrySet()) {
        Item i = entry.getKey();
        if(itemName.equals(i.getItemName())) {
          count += entry.getValue();
        }
    }
    return count;
}
编辑

:编辑计数从 0 开始

how can I find the amount of all the items with that key in the hashmap?

Hash Map键是唯一值。对于任何key,您只有一次value

我必须猜测您要实现的目标,所以我假设以下内容:

  • 映射键是Item的实例
  • 您只有密钥item,并希望在地图中找到相应的条目

你可以做的是:

  1. 使用单独的映射到密钥的Item实例,并使用它来访问计数映射
  2. 创建一个"虚拟"(查找)项,该项目仅获取equals()hashCode方法中使用的数据,并使用它来访问计数映射

示例 1.:

 Map<String, Item> items = ...;
 Integer quantity = stockItems.get(items.get("item"));

示例 2.:

class Item {
  private String key;
  public Item(String key) {
    this.key = key;
  }
  ...
  //equals() and hashCode() should only use the key field
}
Integer quantity = stockItems.get( new Item("item") );

更新

如果键不是项目的唯一属性,则必须遍历映射中的所有条目,检查项目的键是否匹配并自行创建总和。

键在

哈希映射中是唯一的。 因此,您的特定键只能有一个值。

最新更新