使用该containsKey()
方法并检查HashMap中是否存在给定键。
让我们首先创建HashMap并添加一些元素-
//创建一个哈希映射 HashMap hm = new HashMap(); //将元素放入映射 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[]) { //创建一个哈希映射 HashMap hm = new HashMap(); //将元素放入映射 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)); //获取一组条目 Set set = hm.entrySet(); System.out.println("Elements in HashMap..."); //获取一个迭代器 Iterator i = set.iterator(); //显示元素 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