跳到主要内容

Java HashMap containsKey() 方法

containsKey() 方法的语法是:

hashmap.containsKey(Object key)

这里的 hashmapHashMap 类的一个对象。

containsKey() 参数

containsKey() 方法接受单个参数。

  • key - 在 hashmap 中检查 key 的映射

containsKey() 返回值

  • 如果 hashmap 中存在指定 key 的映射,则返回 true
  • 如果 hashmap 中不存在指定 key 的映射,则返回 false

示例 1:Java HashMap 的 containsKey() 方法

import java.util.HashMap;

class Main {
public static void main(String[] args){

// 创建一个 HashMap
HashMap<String, String> details = new HashMap<>();

// 向 HashMap 添加映射
details.put("Name", "Programiz");
details.put("Domain", "mashangxue123.com");
details.put("Location", "Nepal");
System.out.println("Programiz Details: \n" + details);

// 检查键 Domain 是否存在
if(details.containsKey("Domain")) {
System.out.println("Domain name is present in the Hashmap.");
}

}
}

输出

Programiz Details:
{Domain=mashangxue123.com, Name=Programiz, Location=Nepal}
Domain name is present in the Hashmap.

在上面的示例中,我们创建了一个 hashmap。注意表达式,

details.containsKey("Domain") // 返回 true

这里,hashmap 包含键 Domain 的映射。因此,containsKey() 方法返回 true 并执行 if 块内的语句。

示例 2:如果键尚未存在,则向 HashMap 添加条目

import java.util.HashMap;

class Main {
public static void main(String[] args){

// 创建一个 HashMap
HashMap<String, String> countries = new HashMap<>();

// 向 HashMap 添加映射
countries.put("USA", "Washington");
countries.put("Australia", "Canberra");
System.out.println("HashMap:\n" + countries);

// 检查键 Spain 是否存在
if(!countries.containsKey("Spain")) {
// 如果键尚未存在,则添加条目
countries.put("Spain", "Madrid");
}

System.out.println("Updated HashMap:\n" + countries);

}
}

输出

HashMap:
{USA=Washington, Australia=Canberra}
Updated HashMap:
{USA=Washington, Australia=Canberra, Spain=Madrid}

在上述示例中,注意表达式,

if(!countries.containsKey("Spain")) {..}

这里,我们使用了 containsKey() 方法来检查 hashmap 中是否存在 Spain 的映射。由于我们使用了否定符号 (!),如果方法返回 false,则执行 if 块。

因此,只有在 hashmap 中不存在指定 key 的映射时,才会添加新的映射。

注意:我们也可以使用 HashMap 的 putIfAbsent() 方法来执行同样的任务。