您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,HashMap允许使用null作为键(key)和值(value)
使用putIfAbsent()
方法:
当插入一个键值对时,如果该键不存在,则将键值对插入哈希表。如果键已经存在,则不会插入新的值。
HashMap<String, String> hashMap = new HashMap<>();
hashMap.putIfAbsent("key1", "value1");
hashMap.putIfAbsent("key2", "value2");
hashMap.putIfAbsent("key1", "value3"); // 这不会覆盖原有的值 "value1"
使用computeIfAbsent()
方法:
当计算一个键对应的值时,如果该键不存在或对应的值为null,则使用提供的映射函数计算新值并将其插入哈希表。
HashMap<String, String> hashMap = new HashMap<>();
hashMap.computeIfAbsent("key1", k -> "value1");
hashMap.computeIfAbsent("key2", k -> "value2");
hashMap.computeIfAbsent("key1", k -> "value3"); // 这不会覆盖原有的值 "value1"
使用getOrDefault()
方法:
当获取一个键对应的值时,如果该键不存在,则返回默认值。
HashMap<String, String> hashMap = new HashMap<>();
String value1 = hashMap.getOrDefault("key1", "default1");
String value2 = hashMap.getOrDefault("key2", "default2");
String value3 = hashMap.getOrDefault("key3", "default3"); // key3不存在,返回默认值 "default3"
使用remove()
方法:
当删除一个键值对时,如果该键存在,则删除该键值对。
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");
hashMap.remove("key1"); // 删除键为 "key1" 的键值对
使用containsKey()
和containsValue()
方法检查键或值是否存在:
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");
boolean containsKey1 = hashMap.containsKey("key1"); // 返回 true
boolean containsValue2 = hashMap.containsValue("value2"); // 返回 true
boolean containsKey3 = hashMap.containsKey("key3"); // 返回 false
boolean containsValue4 = hashMap.containsValue("value4"); // 返回 false
通过使用这些方法,您可以有效地处理Java哈希表中的空键值对。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。