Menu
Coddy logo textTech

Recap - HashMap

Part of the Logic & Flow section of Coddy's Java journey — lesson 15 of 59.

challenge icon

Challenge

Easy

Create a method named processHashMap that takes a HashMap<String, Integer> and an array of String operations, then performs the following actions:

1. GET Operation

  • Format: "GET key"
  • Action:
    • If the key exists: Print the value
    • If the key doesn't exist: Print "Not found"

2. CHECK Operation

  • Format: "CHECK key"
  • Action:
    • If the key exists: Print "Exists"
    • If the key doesn't exist: Print "Not found"

3. MODIFY Operation

  • Format: "MODIFY key targetValue"
  • Action:
    • If the key exists AND its current value equals targetValue: Use replace() to update the value to targetValue + 1
    • If the key exists BUT its current value is different from targetValue: Use remove() to delete the key
    • If the key doesn't exist: Use put() to add it with targetValue as its value
  • Note: Do NOT print anything during MODIFY operations

Final Output:

After processing all operations, the method should return the modified HashMap. The main method will print it in JSON format.

Try it yourself

// --- Modules to convert string of hashmap to 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> processHashMap(HashMap<String, Integer> data, String[] operations) {
        // Write your code here
    }

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

        // Convert String of HashMap to HashMap
        Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
        HashMap<String, Integer> data = new Gson().fromJson(hashMapString, mapType);

        // Convert String of Array to Array
        String[] operations = new Gson().fromJson(operationsString, String[].class);

        HashMap<String, Integer> result = processHashMap(data, operations);
        System.out.println(new Gson().toJson(result));
    }
}

All lessons in Logic & Flow