딕셔너리 수정하기
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 14번째.
HashMaps는 또한 키를 제거하고 이를 업데이트하는 메서드인 put(), remove(), 그리고 replace()를 지원합니다.
예를 들어 먼저 HashMap을 채워보겠습니다:
HashMap<String, String> users = new HashMap<>();
users.put("alice", "Admin");
users.put("bob", "User");키를 제거하려면:
users.remove("bob"); // Removes "bob"
System.out.println(users);
// {alice=Admin}키를 업데이트하려면:
users.replace("bob", "Guest");
// Updates bob to Guest
users.replace("Charlie", "Admin");
// Does nothing (key "Charlie" doesn't exist)챌린지
쉬움<strong>modifyMap</strong>이라는 이름의 메서드를 작성하여 주어진 HashMap을 특정 조건에 따라 수정하세요.
data라는 이름의 HashMap을 받습니다. 여기서:- 키는
String타입입니다. - 값은
Integer타입입니다.
- 키는
- String
key를 받습니다. - Integer
newValue를 받습니다.
메서드는 다음 규칙을 따라 업데이트된 HashMap을 반환해야 합니다:
data에 키가 존재하고newValue와 동일한 값을 가진 경우,<strong>replace()</strong>를 사용하되 값을 1 증가시킵니다.- 키가 존재하지만 다른 값을 가진 경우, 제거합니다.
- 키가 존재하지 않는 경우,
<strong>newValue</strong>로 추가합니다.
치트 시트
데이터를 수정하는 HashMap 메서드:
키 제거:
users.remove("bob"); // Removes "bob" key-value pair값 업데이트/교체:
users.replace("alice", "Guest"); // Updates existing key
users.replace("nonexistent", "Admin"); // Does nothing if key doesn't exist키 추가 또는 업데이트:
users.put("newUser", "Admin"); // Adds new key or updates existing직접 해보기
// --- 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();
// 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));
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.