102 「Map修羅道」 Step07 解答例

MapUtil.java

import java.util.*;

public class MapUtil {
    public static void printStoreInventory() {
        // 店舗別の商品在庫を記録するMap(ネストされたMap構造)
        // 外側のMap: 店舗名 → 内側のMap
        // 内側のMap: 商品名 → 在庫数
        Map<String, Map<String, Integer>> storeInventory = new HashMap<>();

        // --- データ登録(Tokyo店) ---
        addStock(storeInventory, "Tokyo", "Apple", 10);
        addStock(storeInventory, "Tokyo", "Banana", 5);

        // --- データ登録(Osaka店) ---
        addStock(storeInventory, "Osaka", "Apple", 7);
        addStock(storeInventory, "Osaka", "Orange", 3);

        // --- 出力 ---
        for (String store : storeInventory.keySet()) {
            System.out.println(store + ":");
            Map<String, Integer> products = storeInventory.get(store);
            for (String product : products.keySet()) {
                int stock = products.get(product);
                System.out.println("  " + product + " → " + stock);
            }
        }
    }

    // ヘルパーメソッド:商品在庫を追加する
    private static void addStock(Map<String, Map<String, Integer>> inventory,
                                 String store, String product, int stock) {
        // 店舗が存在しなければ新しくMapを作成
        if (!inventory.containsKey(store)) {
            inventory.put(store, new HashMap<>());
        }
        // 店舗に対応する商品Mapを取得し、商品と在庫を登録
        inventory.get(store).put(product, stock);
    }
}

解説:Mapの中にMap?ネスト構造の使い方

このステップでは、「Mapの中にMapが入る」というやや複雑な構造を扱います。
現実のデータ構造では非常によく使われる形です。


構造の意味

Map<String, Map<String, Integer>> storeInventory;
  • 外側のMap:キーは「店舗名」、値は「商品→在庫数」を管理するMap
  • 内側のMap:キーは「商品名」、値は「在庫数」

データの登録方法

if (!inventory.containsKey(store)) {
    inventory.put(store, new HashMap<>());
}
inventory.get(store).put(product, stock);
  • 店舗が初めて登場した場合、内側のMap(商品一覧)を新規作成
  • すでにある店舗には、商品と在庫を追加登録

出力方法(2重ループ)

for (String store : storeInventory.keySet()) {
    System.out.println(store + ":");
    for (String product : storeInventory.get(store).keySet()) {
        System.out.println("  " + product + " → " + 在庫数);
    }
}
  • 外側のMap(店舗)を回しながら
  • 内側のMap(商品)をさらに回して出力

実行結果の例(順不同)

Tokyo:
  Apple → 10
  Banana → 5
Osaka:
  Apple → 7
  Orange → 3

まとめ:このステップで学ぶべきこと

  • ネストされたMapの構造を作る方法(Map<String, Map<…>>)
  • 初期化の必要性と、ループ構造の正しい組み方
  • 現実的なデータ構造をJavaで扱う力を養う

このステップを理解すれば、複雑な階層構造のデータをJavaで自在に扱えるようになります。

102 ステップアップ問題 「Map修羅道」