检查Java HashMap中是否存在给定键
使用该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
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西