CodeGym /בלוג Java /Random-HE /שיטת HashMap computeIfAbsent() ב-Java
John Squirrels
רָמָה
San Francisco

שיטת HashMap computeIfAbsent() ב-Java

פורסם בקבוצה
Java 8, כפי שרבים מאיתנו יודעים, הציגה את ה- Stream API. זוהי ערכת כלים שימושית מאוד, אך יש לה חיסרון, היא אינה כוללת מפות . עם זאת, Java 8 הוסיפה מספר שיטות שימושיות לממשק המפה עצמו כדי להפחית את כמות הקוד ה"רע". לכן, אם אתה צריך לבצע פעולה כלשהי עם הערך במפה , אם הוא קיים בו, יש שיטה ComputeIfPresent() במפת Java. אם אתה צריך לעשות משהו עם ערך שאינו נמצא במפה , אתה יכול להשתמש בשיטת ComputeIfAbsent() . נשקול זאת במאמר זה.

חתימת השיטה computeIfAbsent().

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
שיטת Map (ו- HashMap ) computeIfAbsent() לוקחת שני פרמטרים. הפרמטר הראשון הוא המפתח. הפרמטר השני הוא ה- mappingFunction . בשיטה זו פונקציית המיפוי נקראת רק אם המיפוי אינו מוצג.

כיצד פועלת שיטת computeIfAbsent()

כפי שאנו כבר יודעים, שיטת Map.computeIfAbsent() מועברת שני פרמטרים, המפתח והפונקציה לחישוב הערך עבור מיפוי מפתח זה . להלן האלגוריתם הלוגי של השיטה:
  1. השיטה בודקת תחילה אם המפתח שעבר מיוצג במפה שלנו .
  2. אם המפתח מיוצג במפה ( והוא לא null), אז השיטה לא עושה כלום.
  3. אחרת, אם המפתח אינו מייצג במפה ( או שהוא null), השיטה מחשבת את הערך באמצעות mappingFunction למפתח.
  4. אם הערך המתקבל אינו ריק, כתוב זוג מפתח-ערך למיפוי.
בוא נכתוב את אותו היגיון כמו קוד:
if (map.get(key) == null)
{
V newValue = mappingFunction.apply(key);
if (newValue != null) map.put(key, newValue);
}

דוגמה לקוד computeIfAbsent().

לכן, אם הערך לא נמצא במפה , השיטה תבצע את השינויים. בואו נסתכל על דוגמה פשוטה:
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"));
       }
}
הפלט הוא:
הנה המפתח שלי, וזה ערך חדש
עכשיו בואו נראה מה השיטה תעשה כאשר יש ערך נתון במפה . התראת ספוילר: זה לא יעשה כלום.
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