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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短