日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java.util.Map中put,computeIfAbsent与putIfAbsent区别

發布時間:2025/3/20 编程问答 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java.util.Map中put,computeIfAbsent与putIfAbsent区别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

computeIfAbsent和putIfAbsent區別是三點:

1、當Key存在的時候,如果Value獲取比較昂貴的話,putIfAbsent就白白浪費時間在獲取這個昂貴的Value上(這個點特別注意)

2、Key不存在的時候,putIfAbsent返回null,小心空指針,而computeIfAbsent返回計算后的值

3、當Key不存在的時候,putIfAbsent允許put null進去,而computeIfAbsent不能,之后進行containsKey查詢是有區別的(當然了,此條針對HashMap,ConcurrentHashMap不允許put null value進去)

4、computeIfAbsent的value是接受一個Function,而putIfAbsent是是接受一個具體的value,所以computeIfAbsent的使用應該是非常靈活的

下面代碼演示:

public V putIfAbsent(K key, V value)

? ? ? ?ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();System.out.println("put:" + map.putIfAbsent("hello", "123"));System.out.println(map.get("hello"));System.out.println("put:" + map.putIfAbsent("hello", "456"));System.out.println(map.get("hello"));

輸入如下:

put:null 123 put:123 123

putIfAbsent會返回之前的值,如果之前不存在,則返回null;而且put一個存在的key時,并不會覆蓋掉之前的key。

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

? ? ? ?ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();System.out.println("put:" + map.computeIfAbsent("world", s -> "java"));System.out.println(map.get("world"));System.out.println("put:" + map.computeIfAbsent("world", s -> "php"));System.out.println(map.get("world"));

輸出如下:

put:java java put:java java

computeIfAbsent會返回本次計算的值,同時如果put的也是一個存在的key時,也不會覆蓋掉之前的key。

public V put(K key, V value)

? ? ? ?ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();System.out.println("put:" + map.put("test", "python"));System.out.println(map.get("test"));System.out.println("put:" + map.put("test", "javascript"));System.out.println(map.get("test"));

輸出如下:

put:null python put:python javascript

put會返回之前的值,如果之前不存在,則返回null。每次put的時候,都會更新對應的key值。

總結:

是否覆蓋value返回值返回值
put覆蓋前
putIfAbsent覆蓋前
computeIfAbsent覆蓋后

總結

以上是生活随笔為你收集整理的java.util.Map中put,computeIfAbsent与putIfAbsent区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。