Java 程序检查给定值是否存在于 HashMap 中


使用 containsValue() 方法检查给定值是否存在于 HashMap 中。

首先,让我们创建一个 HashMap 并添加一些元素——

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));

现在让我们检查给定的值是否存在。在此,我们检查值“800”——

hm.containsValue(800);

以下示例检查给定值是否存在于 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 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

更新日期:30-7-2019

3K+ 浏览

开启您的职业生涯

通过完成课程获得认证

入门
广告