Java程序检查HashMap中是否存在给定值
使用该containsValue()
方法检查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));
现在让我们检查给定值是否存在。在这里,我们正在检查值“ 800”-
hm.containsValue(800);
以下是检查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 key Bag exist in the HashMap = "+hm.containsKey("Bag"));
System.out.println("Does value 800 exist in the HashMap = "+hm.containsValue(800));
}
}
输出结果
Elements in HashMap...Frames: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000
Does key Bag exist in the HashMap = true
Does value 800 exist in the HashMap = true
以上是 Java程序检查HashMap中是否存在给定值 的全部内容, 来源链接: utcz.com/z/334714.html