중첩 HashMap
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨. 59개 중 19번째.
중첩된 HashMap은 값 자체가 HashMap인 HashMap입니다. 이를 통해 복잡한 데이터를 계층적으로 구성할 수 있습니다. 예를 들어, 카테고리(예: "Electronics" 또는 "Furniture")를 제품과 가격을 담고 있는 inner HashMap에 매핑하는 outer HashMap을 만들 수 있습니다.
중첩된 HashMap을 생성합니다: categories -> (items -> prices)
HashMap<String, HashMap<String, Integer>> inventory = new HashMap<>();빈 내부 HashMap과 함께 "Electronics" 카테고리를 추가하세요
inventory.put("Electronics", new HashMap<>());가격이 1200인 "Laptop" 항목을 "Electronics"에 추가합니다
inventory.get("Electronics").put("Laptop", 1200);outer map이 비어 있는지 확인하고 크기를 출력합니다
System.out.println(inventory.isEmpty());
// 출력: false
System.out.println(inventory.size());
// 출력: 1이 예제에서 외부 map에는 키 하나("Electronics")가 있으며, 이 키는 키 "Laptop"과 해당 값 1200을 포함하는 내부 HashMap에 매핑됩니다.
챌린지
쉬움<b>printNestedInventory</b>라는 이름의 메서드를 만들고, 중첩된 inventory라는 HashMap을 입력으로 받으세요. 이 inventory에서:
- 키는 카테고리입니다(예: "Electronics", "Furniture").
- 값은 키가 제품 이름이고 값이 해당 제품의 가격인 내부 HashMap입니다.
메서드는 다음 형식으로 inventory를 출력해야 합니다:
- 각 카테고리에 대해
Category: <name>을 출력합니다. - 카테고리에 제품이 있으면 각 제품을
Product: <name>, Price: <price>형식으로 출력합니다(2칸 들여쓰기). - 카테고리에 제품이 없으면
(No products)를 출력합니다(2칸 들여쓰기).
출력 예시:
Category: Electronics
Product: Laptop, Price: 1200
Product: Smartphone, Price: 800
Category: Furniture
Product: Chair, Price: 50
Product: Table, Price: 150
Category: EmptyCategory
(No products)참고: HashMap은 반복 순서를 보장하지 않으므로 출력에서 카테고리와 제품의 순서가 위 예시와 다를 수 있습니다. 이는 예상된 동작입니다.
참고: 다른 제공된 import 외에도 java.util.Map을 import해야 합니다.
직접 해보기
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void printNestedInventory(HashMap<String, HashMap<String, Integer>> inventory) {
// 외부 HashMap의 각 카테고리를 순회합니다
// 각 카테고리에 대해 "Category: <name>"을 출력합니다
// 내부 맵이 비어 있으면 " (No products)"를 출력합니다
// 그렇지 않으면 각 제품을 순회하며 " Product: <name>, Price: <price>"를 출력합니다
// 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String inventoryString = scanner.nextLine();
// JSON 문자열을 Nested HashMap으로 변환합니다
Type inventoryType = new TypeToken<HashMap<String, HashMap<String, Integer>>>(){}.getType();
HashMap<String, HashMap<String, Integer>> inventory = new Gson().fromJson(inventoryString, inventoryType);
printNestedInventory(inventory);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 Java 컴파일러