CodeGym /Java Blog /Toto sisi /Java 中的 HashMap computeIfAbsent() 方法
John Squirrels
等級 41
San Francisco

Java 中的 HashMap computeIfAbsent() 方法

在 Toto sisi 群組發布
眾所周知,Java 8 引入了 Stream API。這是一個非常有用的工具包,但它有一個缺點,它不包含Map。但是,Java 8 向Map接口本身添加了幾個有用的方法,以減少“壞”代碼的數量。因此,如果您需要對Map中的值執行某些操作,如果它存在於其中,則Java Map 中有一個ComputeIfPresent()方法。如果您需要對不在Map中的值執行某些操作,則可以使用ComputeIfAbsent()方法。我們將在本文中考慮它。

computeIfAbsent() 方法簽名


default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
Map (和HashMapcomputeIfAbsent ()方法有兩個參數。第一個參數是鍵。第二個參數是mappingFunction。在此方法中,僅當未提供映射時才調用映射函數。

computeIfAbsent() 方法的工作原理

正如我們已經知道的,Map.computeIfAbsent()方法被傳遞了兩個參數,鍵和用於計算該鍵的值的函數mappingFunction。這是該方法的邏輯算法:
  1. 該方法首先檢查傳遞的鍵是否在我們的Map中表示。
  2. 如果鍵在Map中表示(並且它不為空),則該方法不執行任何操作。
  3. 否則,如果鍵不在Map中表示(或者它為空),則該方法使用鍵的mappingFunction計算值。
  4. 如果結果值不為空,則寫一個鍵值對映射。
讓我們編寫與代碼相同的邏輯:

if (map.get(key) == null) 
{ 
V newValue = mappingFunction.apply(key); 
if (newValue != null) map.put(key, newValue); 
}

computeIfAbsent() 代碼示例

因此,如果該值不在Map中,則該方法將執行更改。讓我們看一個簡單的例子:

import java.util.HashMap;
import java.util.Map;

//map.computeIfAbsent example 
public class ComputeIfAbsentExample {

       public static void main(String[] args) {

           Map<String, String> myMap = new HashMap<>();

           myMap.computeIfAbsent("here is my key", key -> key + ", " + "and this is a new value");

           System.out.println(myMap.get("here is my key"));
       }
}
輸出是:
這是我的鑰匙,這是一個新值
現在讓我們看看當Map 中有給定值時該方法將做什麼。劇透警報:它不會做任何事情。

import java.util.HashMap;
import java.util.Map;

public class ComputeIfAbsentExample2 {

       public static void main(String[] args) {

           Map<String, String> myMap = new HashMap<>();
           myMap.put("here is my key", "and here is my value");

           myMap.computeIfAbsent("here is my key", key -> key + ", " + "and this is a new value");

           System.out.println(myMap.get("here is my key"));
       }
}
這是輸出:
這是我的價值
如您所見,該值保持不變。

另一個 ComputeIfAbsent() 示例

如果您熟悉緩存的概念,computeIfAbsent()方法可能會讓您想起一些事情。讓我們看一個更複雜的解析示例。讓我們調用computeIfAbsent()方法兩次,以確保在第一種情況下值發生變化,而在第二種情況下則不會。

import java.util.HashMap;
import java.util.Map;

public class ComputeIfAbsentExample {
   private static Map<String, Long> numbersMap = new HashMap<>();

   public static Long stringToLong(String str) {
       return numbersMap.computeIfAbsent(str, key -> {
           System.out.println("parsing: " + key);
           return Long.parseLong(key);
       });
   }

   public static void main(String[] args) {
       // will print:
       // > parsing: 10
       // > parsing: 25
       // > 10+25=35
       System.out.println("10+25=" + (stringToLong("10") + stringToLong("25")));
       // will print:
       // > parsing: 20
       // > 10+25=45
       // only "20" will be parsed this time, since "25" was already parsed and placed into `numbersMap` map before
       System.out.println("20+25=" + (stringToLong("20") + stringToLong("25")));
       // will print:
       // > 10+20=30
       // no parsing will occur, since both "10" and "20" were already parsed and placed into `numbersMap` map before
       System.out.println("10+20=" + (stringToLong("10") + stringToLong("20")));
   }

}
這是輸出:
解析:10 解析:25 10+25=35 解析:20 20+25=45 10+20=30
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION