keySet()으로 반복하기
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨. 59개 중 17번째.
keySet()을 사용해 반복한다는 것은 HashMap의 모든 키가 들어 있는 집합을 얻은 다음, get() 메서드를 사용해 해당하는 값을 가져온다는 뜻입니다. 이는 간단하며 작은 맵에서 잘 작동합니다.
먼저, 제품의 HashMap을 만드세요:
HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("Laptop", 10);
inventory.put("Mouse", 50);
inventory.put("Keyboard", 30);이제 keySet()을 사용해 반복하세요:
for (String product : inventory.keySet()) {
int quantity = inventory.get(product);
System.out.println("Product: " +
product + ", Quantity: " + quantity);
}
// Product: Laptop, Quantity: 10
// Product: Mouse, Quantity: 50
// Product: Keyboard, Quantity: 30챌린지
쉬움printInventoryKeySet라는 메서드를 만들어 Scanner를 통해 읽은 JSON 문자열에서 가져온 HashMap(키는 제품 이름이고 값은 수량)을 매개변수로 받도록 하세요. 메서드는 keySet() 메서드를 사용해 HashMap을 반복하며 각 키-값 쌍을 다음 형식으로 출력해야 합니다:
Product: <product name>, Quantity: <quantity>직접 해보기
import java.util.HashMap;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Main {
public static void printInventoryKeySet(HashMap<String, Integer> inventory) {
// keySet()을 사용하여 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// inventory HashMap을 나타내는 JSON 문자열 입력을 읽으세요
String inventoryString = scanner.nextLine();
// JSON 문자열을 HashMap<String, Integer>로 변환하세요
Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
HashMap<String, Integer> inventory = new Gson().fromJson(inventoryString, mapType);
printInventoryKeySet(inventory);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 Java 컴파일러