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
EasyWrite a method named <strong>modifyMap</strong> that modifies a given HashMap based on specific conditions.
- Takes a HashMap named
datawhere:- Keys are of type
String. - Values are of type
Integer.
- Keys are of type
- Takes a String
key. - Takes an Integer
newValue.
The method should return the updated HashMap by following:
- If the key exists in
dataand has the same value asnewValue, 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 pairUpdate/replace a value:
users.replace("alice", "Guest"); // Updates existing key
users.replace("nonexistent", "Admin"); // Does nothing if key doesn't existAdd or update a key:
users.put("newUser", "Admin"); // Adds new key or updates existingTry 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));
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap