📜  地图中是否存在键 (1)

📅  最后修改于: 2023-12-03 15:37:47.544000             🧑  作者: Mango

判断地图中是否存在键

当我们使用地图(Map)这种数据类型时,面对某些需要判断地图中是否存在特定键(key)的需求,这时候我们可以使用一些方法来完成这个任务。

方法一:使用containsKey方法

这种方式最为常见,它使用Map接口中的containsKey(Object key)方法来判断地图中是否存在特定键。

示例代码:

Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

if (map.containsKey("key1")) {
    System.out.println("map contains key \"key1\".");
} else {
    System.out.println("map does not contain key \"key1\".");
}

Markdown代码片段:

## 方法一:使用containsKey方法

这种方式最为常见,它使用Map接口中的`containsKey(Object key)`方法来判断地图中是否存在特定键。

示例代码:

````java
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

if (map.containsKey("key1")) {
    System.out.println("map contains key \"key1\".");
} else {
    System.out.println("map does not contain key \"key1\".");
}
方法二:使用get方法

这种方式也能判断地图中是否存在特定键,它使用Map接口中的get(Object key)方法来获取键所对应的值,当返回值为null时,表示地图中不存在该键。

示例代码:

Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

if (map.get("key1") != null) {
    System.out.println("map contains key \"key1\".");
} else {
    System.out.println("map does not contain key \"key1\".");
}

Markdown代码片段:

## 方法二:使用get方法

这种方式也能判断地图中是否存在特定键,它使用Map接口中的`get(Object key)`方法来获取键所对应的值,当返回值为`null`时,表示地图中不存在该键。

示例代码:

````java
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

if (map.get("key1") != null) {
    System.out.println("map contains key \"key1\".");
} else {
    System.out.println("map does not contain key \"key1\".");
}
方法三:使用keySet方法

这种方式可以得到地图中所有的键集合后,再遍历这个集合判断地图中是否存在特定键。

示例代码:

Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

boolean isExist = false;
for (String key : map.keySet()) {
    if (key.equals("key1")) {
        isExist = true;
        break;
    }
}

if (isExist) {
    System.out.println("map contains key \"key1\".");
} else {
    System.out.println("map does not contain key \"key1\".");
}

Markdown代码片段:

## 方法三:使用keySet方法

这种方式可以得到地图中所有的键集合后,再遍历这个集合判断地图中是否存在特定键。

示例代码:

````java
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

boolean isExist = false;
for (String key : map.keySet()) {
    if (key.equals("key1")) {
        isExist = true;
        break;
    }
}

if (isExist) {
    System.out.println("map contains key \"key1\".");
} else {
    System.out.println("map does not contain key \"key1\".");
}

以上是三种判断地图中是否存在键的方法,它们各有优缺点,程序员可以根据具体情况进行选择。