Menu
CoddyTech

تعديل القواميس

جزء من قسم المنطق وتدفق التنفيذ في رحلة Java على Coddy. الدرس 14 من 59.

تدعم خرائط التجزئة أيضًا إزالة المدخلات وتحديثها باستخدام التوابع put() وremove() وreplace().

على سبيل المثال، لنملأ HashMap أولاً:

HashMap<String, String> users = new HashMap<>();
users.put("alice", "Admin");
users.put("bob", "User");

لإزالة مفتاح:

users.remove("bob"); // يزيل "bob"
System.out.println(users);
// {alice=Admin}

لتحديث مفتاح:

users.replace("alice", "Guest");
// يحدّث alice إلى Guest

users.replace("Charlie", "Admin");
// لا يفعل شيئًا (المفتاح "Charlie" غير موجود)
challenge icon

التحدي

سهل

اكتب دالة باسم modifyMap تعدّل HashMap معطاة وفقًا لشروط محددة.

  1. تأخذ HashMap باسم data حيث:
    • المفاتيح من النوع String.
    • القيم من النوع Integer.
  2. تأخذ String key.
  3. تأخذ Integer newValue.

يجب أن تعيد الدالة HashMap المحدّثة باتباع ما يلي:

  • إذا كان المفتاح موجودًا في data وكانت له القيمة نفسها مثل newValue، فاستخدم replace() مع زيادة القيمة بمقدار 1.
  • إذا كان المفتاح موجودًا ولكن له قيمة مختلفة، فأزِله.
  • إذا لم يكن المفتاح موجودًا، فأضِفه بالقيمة newValue.

جرّب بنفسك

// --- وحدات لتحويل سلسلة نصية تمثل hashmap إلى hashmap ---
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
// -----------------------------
import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static HashMap<String, Integer> modifyMap(HashMap<String, Integer> data, String key, int newValue) {
        // اكتب التعليمات البرمجية الخاصة بك هنا
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String hashMapString = scanner.nextLine();
        String key = scanner.nextLine();
        int newValue = scanner.nextInt();

        // حوّل String من HashMap إلى HashMap
        Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
        HashMap<String, Integer> data = new Gson().fromJson(hashMapString, mapType);

        HashMap<String, Integer> result = modifyMap(data, key, newValue);
        System.out.println(new Gson().toJson(result));
    }
}
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس المنطق وتدفق التنفيذ

تدرّب بنفسك: مترجم Java عبر الإنترنت