Java 如何检查一个键是否存在于HashMap中

Java 如何检查一个键是否存在于HashMap中

在Java中给定一个HashMap和一个键,任务是检查这个键是否存在于HashMap中。

例子

Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2
输出: true

Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10
输出: false

建议:请先在{IDE}上尝试你的方法,然后再继续解决

  1. 使用迭代器(效率不高) :
    1. 获取HashMap和密钥
    2. 创建一个迭代器,使用HashMap.iterate()方法在HashMap上进行迭代。
    3. 使用Iterator.hasNext()方法遍历HashMap。
    4. 在迭代的同时,检查该迭代的键是否与指定的键相等。Map的入口键可以在 entry.getKey() 方法的帮助下获得。
    5. 如果键值匹配,将标志设置为 “true”。
    6. 迭代后的标志值,包含了结果。

下面是上述方法的实现。

程序 1:

    // Java program to check if a key exists
    // in a HashMap or not
      
    import java.util.*;
      
    public class GFG {
        public static void main(String[] args)
        {
      
            // Create a HashMap
            HashMap<Integer, String>
                map = new HashMap<>();
      
            // Populate the HashMap
            map.put(1, "Geeks");
            map.put(2, "ForGeeks");
            map.put(3, "GeeksForGeeks");
      
            // Get the key to be removed
            int keyToBeChecked = 2;
      
            // Print the initial HashMap
            System.out.println("HashMap: "
                               + map);
      
            // Get the iterator over the HashMap
            Iterator<Map.Entry<Integer, String> >
                iterator = map.entrySet().iterator();
      
            // flag to store result
            boolean isKeyPresent = false;
      
            // Iterate over the HashMap
            while (iterator.hasNext()) {
      
                // Get the entry at this iteration
                Map.Entry<Integer, String>
                    entry
                    = iterator.next();
      
                // Check if this key is the required key
                if (keyToBeChecked == entry.getKey()) {
      
                    isKeyPresent = true;
                }
            }
      
            // Print the result
            System.out.println("Does key "
                               + keyToBeChecked
                               + " exists: "
                               + isKeyPresent);
        }
    }

输出:

HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}
Does key 2 exists: true

程序2:为了说明为什么不建议使用这个方法。如果HashMap包含空值,那么这个方法将抛出NullPointerException。这使得这个方法不建议使用。

// Java program to check if a key exists
// in a HashMap or not
  
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        try {
            // Create a HashMap
            HashMap<Integer, String>
                map = new HashMap<>();
  
            // Populate the HashMap
            map.put(1, "Geeks");
            map.put(2, "ForGeeks");
            map.put(null, "GeeksForGeeks");
  
            // Get the key to be removed
            int keyToBeChecked = 2;
  
            // Print the initial HashMap
            System.out.println("HashMap: "
                               + map);
  
            // Get the iterator over the HashMap
            Iterator<Map.Entry<Integer, String> >
                iterator = map.entrySet().iterator();
  
            // flag to store result
            boolean isKeyPresent = false;
  
            // Iterate over the HashMap
            while (iterator.hasNext()) {
  
                // Get the entry at this iteration
                Map.Entry<Integer, String>
                    entry
                    = iterator.next();
  
                // Check if this key is the required key
                if (keyToBeChecked == entry.getKey()) {
  
                    isKeyPresent = true;
                }
            }
  
            // Print the result
            System.out.println("Does key "
                               + keyToBeChecked
                               + " exists: "
                               + isKeyPresent);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}
java.lang.NullPointerException
  1. 使用HashMap.containsKey方法(Efficient)。
    1. 获取HashMap和Key
    2. 使用HashMap.containsKey()方法检查键是否存在于HashMap中。如果键存在,则将标记设为 “true”。
    3. flag值,包含结果。

下面是上述方法的实现。

程序1:

// Java program to check if a key exists
// in a HashMap or not
  
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Create a HashMap
        HashMap<Integer, String>
            map = new HashMap<>();
  
        // Populate the HashMap
        map.put(1, "Geeks");
        map.put(2, "ForGeeks");
        map.put(null, "GeeksForGeeks");
  
        // Get the key to be removed
        int keyToBeChecked = 2;
  
        // Print the initial HashMap
        System.out.println("HashMap: "
                           + map);
  
        // Check is key exists in the Map
        boolean isKeyPresent = map.containsKey(keyToBeChecked);
  
        // Print the result
        System.out.println("Does key "
                           + keyToBeChecked
                           + " exists: "
                           + isKeyPresent);
    }
}

输出:

HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}
Does key 2 exists: true

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程