杰瑞科技汇

Java如何高效获取Map中的value值?

get(K key)

这是最直接、最常用的方法,它通过你提供的 key 来获取对应的 value

Java如何高效获取Map中的value值?-图1
(图片来源网络,侵删)

基本用法

get() 方法的签名是 V get(Object key)

  • 参数key,你想要查找的键。
  • 返回值
    • Map 中存在该 key,则返回对应的 value
    • key 不存在,则返回 null

示例代码:

import java.util.HashMap;
import java.util.Map;
public class GetValueExample {
    public static void main(String[] args) {
        // 1. 创建一个 Map 并初始化
        Map<String, Integer> studentScores = new HashMap<>();
        studentScores.put("Alice", 95);
        studentScores.put("Bob", 88);
        studentScores.put("Charlie", 92);
        // 2. 使用 get() 方法获取 value
        Integer alicesScore = studentScores.get("Alice"); // key 存在
        Integer davesScore = studentScores.get("Dave");   // key 不存在
        System.out.println("Alice's score: " + alicesScore); // 输出: Alice's score: 95
        System.out.println("Dave's score: " + davesScore);   // 输出: Dave's score: null
    }
}

重要注意事项:get() 返回 null 的情况

get() 方法在 key 不存在时返回 null,这可能会带来一个问题:value 本身就可以是 null,那么你无法通过返回值 null 来区分是“key 不存在”还是“key 存在但其 valuenull”。

示例:

Java如何高效获取Map中的value值?-图2
(图片来源网络,侵删)
Map<String, String> config = new HashMap<>();
config.put("timeout", "30");
config.put("debug_mode", null); // 一个合法的 value 为 null 的项
String timeout = config.get("timeout"); // 返回 "30"
String debugMode = config.get("debug_mode"); // 返回 null
String nonExistentKey = config.get("non_existent_key"); // 也返回 null
// 你无法区分 debugMode 和 nonExistentKey 的区别
if (debugMode == null) {
    // 这里的代码既可能因为 key 不存在而执行,也可能因为 value 为 null 而执行
    System.out.println("无法确定是 key 不存在还是 value 为 null");
}

进阶用法:安全地获取 value

为了解决上述 null 带来的歧义,Java 提供了更安全的方法。

使用 getOrDefault(K key, V defaultValue)

这个方法非常实用。key 存在,返回其 valuekey 不存在,则返回你指定的默认值,而不是 null

语法V getOrDefault(Object key, V defaultValue)

示例代码:

Java如何高效获取Map中的value值?-图3
(图片来源网络,侵删)
import java.util.HashMap;
import java.util.Map;
public class GetOrDefaultExample {
    public static void main(String[] args) {
        Map<String, String> config = new HashMap<>();
        config.put("timeout", "30");
        // debug_mode 键不存在
        // 使用 getOrDefault
        String timeout = config.getOrDefault("timeout", "60"); // key 存在,返回 "30"
        String debugMode = config.getOrDefault("debug_mode", "false"); // key 不存在,返回默认值 "false"
        System.out.println("Timeout: " + timeout);       // 输出: Timeout: 30
        System.out.println("Debug Mode: " + debugMode); // 输出: Debug Mode: false
    }
}

使用 containsKey(K key) 进行双重检查

如果你非常需要区分“key 不存在”和“valuenull”的情况,可以先检查 key 是否存在,然后再获取 value

语法

  1. map.containsKey(key):检查 Map 是否包含该 key,返回 boolean
  2. map.get(key):在确认 key 存在后获取 value

示例代码:

import java.util.HashMap;
import java.util.Map;
public class ContainsKeyExample {
    public static void main(String[] args) {
        Map<String, String> config = new HashMap<>();
        config.put("timeout", "30");
        config.put("debug_mode", null);
        String keyToCheck = "debug_mode";
        if (config.containsKey(keyToCheck)) {
            // key 存在,再获取 value
            String value = config.get(keyToCheck);
            System.out.println(keyToCheck + " exists, its value is: " + value); // 输出: debug_mode exists, its value is: null
        } else {
            // key 不存在
            System.out.println(keyToCheck + " does not exist.");
        }
        String anotherKey = "non_existent_key";
        if (!config.containsKey(anotherKey)) {
            System.out.println(anotherKey + " does not exist."); // 输出: non_existent_key does not exist.
        }
    }
}

Java 8+ 新特性:getOrDefaultcomputeIfAbsent

Java 8 引入的 Stream API 和新的 Map 方法让操作更加函数式和简洁。

使用 computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

这个方法非常有用,它会检查 key 是否存在:

  • key 不存在,它会使用你提供的 Function 来计算一个 value,然后将 (key, value) 存入 Map 并返回这个 value
  • key 已存在,它不会执行计算,直接返回现有的 value

适用场景:延迟初始化、缓存、避免重复计算等。

示例代码:

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class ComputeIfAbsentExample {
    public static void main(String[] args) {
        Map<String, Integer> wordCount = new HashMap<>();
        // 第一次获取 "apple",key 不存在,会执行计算并存入 Map
        Integer count1 = wordCount.computeIfAbsent("apple", k -> 1); // 使用 lambda k -> 1
        System.out.println("Count for 'apple': " + count1); // 输出: Count for 'apple': 1
        System.out.println("Map: " + wordCount); // 输出: Map: {apple=1}
        // 第二次获取 "apple",key 已存在,直接返回现有值,lambda 不会执行
        Integer count2 = wordCount.computeIfAbsent("apple", k -> 100);
        System.out.println("Count for 'apple' again: " + count2); // 输出: Count for 'apple' again: 1
        System.out.println("Map: " + wordCount); // Map 没有变化: {apple=1}
        // 获取 "banana",key 不存在,执行计算并存入
        Integer count3 = wordCount.computeIfAbsent("banana", String::length); // 使用方法引用
        System.out.println("Count for 'banana': " + count3); // 输出: Count for 'banana': 6
        System.out.println("Map: " + wordCount); // 输出: Map: {apple=1, banana=6}
    }
}

总结与最佳实践

场景 推荐方法 说明
简单获取,确定 key 一定存在 map.get(key) 性能最好,但如果 key 不确定存在,需注意 NullPointerException
简单获取,key 可能不存在 map.getOrDefault(key, defaultValue) 最推荐,代码清晰,避免了 null 的歧义,提供了默认值。
需要区分 key 不存在和 valuenull if (map.containsKey(key)) { map.get(key); } 逻辑严谨,但代码稍显冗长。
获取 value,如果不存在则计算并缓存 map.computeIfAbsent(key, function) 功能强大,适用于延迟加载、缓存等场景,代码简洁且高效。

简单记忆法则:

  • 如果只是想安全地拿到一个值,key 不存在时有默认值,就用 getOrDefault
  • 如果想在 key 不存在时执行一些计算(比如从数据库加载、创建新对象等),就用 computeIfAbsent
  • 只有在特殊业务逻辑下,才需要用 containsKey 进行双重判断。
分享:
扫描分享到社交APP
上一篇
下一篇