Menu
CoddyTech

요약 - HashMap

Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨. 59개 중 15번째.

challenge icon

챌린지

쉬움

processHashMap라는 이름의 메서드를 만들어 HashMap<String, Integer>와 String 연산 배열을 인수로 받아 다음 작업을 수행하세요:

1. GET 연산

  • 형식: "GET key"
  • 작업:
    • 키가 존재하면: 값을 출력합니다
    • 키가 존재하지 않으면: "Not found"을 출력합니다

2. CHECK 연산

  • 형식: "CHECK key"
  • 작업:
    • 키가 존재하면: "Exists"를 출력합니다
    • 키가 존재하지 않으면: "Not found"을 출력합니다

3. MODIFY 연산

  • 형식: "MODIFY key targetValue"
  • 작업:
    • 키가 존재하고 현재 값이 targetValue와 같으면: replace()를 사용해 값을 targetValue + 1로 업데이트합니다
    • 키가 존재하지만 현재 값이 targetValue와 다르면: remove()를 사용해 키를 삭제합니다
    • 키가 존재하지 않으면: put()을 사용해 targetValue를 값으로 추가합니다
  • 참고: MODIFY 연산 중에는 아무것도 출력하지 마세요

최종 출력:

모든 연산을 처리한 후 메서드는 수정된 HashMap을 반환해야 합니다. main 메서드가 이를 JSON 형식으로 출력합니다.

직접 해보기

// --- 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> processHashMap(HashMap<String, Integer> data, String[] operations) {
        // 여기에 코드를 작성하세요
    }

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

        // HashMap 문자열을 HashMap으로 변환
        Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
        HashMap<String, Integer> data = new Gson().fromJson(hashMapString, mapType);

        // Array 문자열을 Array로 변환
        String[] operations = new Gson().fromJson(operationsString, String[].class);

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

논리와 흐름의 모든 레슨

직접 연습해 보세요: 온라인 Java 컴파일러