containsKey()
方法的语法是
hashmap.containsKey(Object key)
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){
// create a HashMap
HashMap<String, String> details = new HashMap<>();
// add mappings to HashMap
details.put("Name", "Programiz");
details.put("Domain", "programiz.com");
details.put("Location", "Nepal");
System.out.println("Programiz Details: \n" + details);
// check if key Domain is present
if(details.containsKey("Domain")) {
System.out.println("Domain name is present in the Hashmap.");
}
}
}
输出
Programiz Details: {Domain=programiz.com, Name=Programiz, Location=Nepal} Domain name is present in the Hashmap.
在上面的示例中,我们创建了一个 HashMap。请注意以下表达式:
details.containsKey("Domain") // returns true
在这里,HashMap 包含 Domain 键的映射。因此,containsKey()
方法返回 true
,并且执行了 if
块内的语句。
示例 2:如果键不存在,则将条目添加到 HashMap
import java.util.HashMap;
class Main {
public static void main(String[] args){
// create a HashMap
HashMap<String, String> countries = new HashMap<>();
// add mappings to HashMap
countries.put("USA", "Washington");
countries.put("Australia", "Canberra");
System.out.println("HashMap:\n" + countries);
// check if key Spain is present
if(!countries.containsKey("Spain")) {
// add entry if key already not present
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() 方法来执行相同的任务。