java map判断是否有键_检查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
總結
以上是生活随笔為你收集整理的java map判断是否有键_检查Java HashMap中是否存在给定键的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 运行时路径_如何在运行时检查当
- 下一篇: java 中random类使用_Java