檢查 Java HashMap 中是否存在給定鍵


使用 containsKey() 方法並檢查給定的鍵在 HashMap 中是否存在。

讓我們先建立 HashMap 並新增一些元素 -

// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));

現在,假設我們需要檢查鍵“Bag”是否存在,為此,請像這樣使用 containsKey() 方法 -

hm.containsKey("Bag")

下面是檢查給定鍵在 HashMap 中是否存在的一個示例 -

示例

 線上示例

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      // Get a set of the entries
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      System.out.println("Does Bag exist in the HashMap = "+hm.containsKey("Bag"));
   }
}

輸出

Elements in HashMap...
Frames: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000
Does Bag exist in the HashMap = true

更新於: 30-Jul-2019

8K+ 瀏覽

開啟您的 職業發展

完成課程即可獲得認證

開始
廣告
© . All rights reserved.