检查 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP