entrySet() を使用したイテレーション
CoddyのJavaジャーニー「ロジックとフロー」セクションの一部。レッスン 18/59。
entrySet()を使って反復処理を行うとは、HashMapからMap.Entryオブジェクトのセットを取得することを意味します。各Map.Entryはキーとそれに対応する値の両方を提供するため、keySet()で必要となる余分な検索を避けられ、より効率的です。
HashMapを作成します:
HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("Laptop", 10);
inventory.put("Mouse", 50);
inventory.put("Keyboard", 30);entrySet()を使って反復処理します:
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.println("Product: " +
entry.getKey() + ", Quantity: " +
entry.getValue());
}
// Product: Laptop, Quantity: 10
// Product: Mouse, Quantity: 50
// Product: Keyboard, Quantity: 30チャレンジ
簡単Scanner を使って読み取った JSON 文字列から、HashMap(キーが商品名、値が数量)を受け取る printInventoryEntrySet という名前のメソッドを作成してください。このメソッドでは、entrySet() メソッドを使って HashMap を反復処理し、各キーと値のペアを次の形式で出力してください。
Product: <product name>, Quantity: <quantity>自分で試してみよう
import java.util.HashMap;
import java.util.Map;
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 printInventoryEntrySet(HashMap<String, Integer> inventory) {
// entrySet()を使ってここにコードを書いてください
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
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);
printInventoryEntrySet(inventory);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
3HashMap 第2部
HashMap のメソッドkeySet() を使用したイテレーションentrySet() を使用したイテレーションネストした HashMap復習 - 倉庫管理復習 - HashMap 操作自分で練習してみよう: Javaオンラインコンパイラ