Menu
Coddy logo textTech

Modifying Dictionaries

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

HashMaps also support removing keys and updating them methods the methods put(), remove(), and replace().

For example let's populate a HashMap first:

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

To remove a key:

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

To update a key:

users.replace("bob", "Guest");
// Updates bob to Guest

users.replace("Charlie", "Admin");
// Does nothing (key "Charlie" doesn't exist)
challenge icon

Challenge

Easy

Write a method named <strong>modifyMap</strong> that modifies a given HashMap based on specific conditions.

  1. Takes a HashMap named data where:
    • Keys are of type String.
    • Values are of type Integer.
  2. Takes a String key.
  3. Takes an Integer newValue.

The method should return the updated HashMap by following:

  • If the key exists in data and has the same value as newValue, use <strong>replace()</strong> but increase the value by 1.
  • If the key exists but has a different value, remove it.
  • If the key does not exist, add it with <strong>newValue</strong>.

Cheat sheet

HashMap methods for modifying data:

Remove a key:

users.remove("bob"); // Removes "bob" key-value pair

Update/replace a value:

users.replace("alice", "Guest"); // Updates existing key
users.replace("nonexistent", "Admin"); // Does nothing if key doesn't exist

Add or update a key:

users.put("newUser", "Admin"); // Adds new key or updates existing

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> modifyMap(HashMap<String, Integer> data, String key, int newValue) {
        // Write your code here
    }

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

        // Convert String of HashMap to 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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow