開始使用免費開始

以標準化後的類別進行分組

你已經將電子產品庫存的類別標準化了。接下來想計算各類別的數量。請將數量彙總為每個類別的總和。

本練習屬於課程

使用 Java 進行資料清理

檢視課程

練習說明

  • 定義一個 enum 對映,在 stockByCategory 中儲存每個 ProductCategory 的數量。
  • stockByCategory 中將數量合併為各類別的總和。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class ElectronicsCategoryExample {
    public enum ProductCategory {
        ELECTRONICS,
        HOME_APPLIANCES,
        UNCATEGORIZED;
    }

    public static void main(String[] args) {
    	Map categoryMap = new HashMap<>();
        categoryMap.put("Home Appliances", ProductCategory.HOME_APPLIANCES);
        categoryMap.put("home appliances", ProductCategory.HOME_APPLIANCES);
        categoryMap.put("HomeAppliances", ProductCategory.HOME_APPLIANCES);
        categoryMap.put("Electronics", ProductCategory.ELECTRONICS);
        categoryMap.put("electronics", ProductCategory.ELECTRONICS);
        categoryMap.put("Electronic", ProductCategory.ELECTRONICS);
        
        Map rawData = Map.of(
                "Home Appliances", 50,
                "home appliances", 25,
                "HomeAppliances", 15,
                "Electronics", 30,
                "electronics", 20,
                "Electronic", 10);

        // Define an enum map to store the quantity of each ProductCategory
        Map stockByCategory = new ____<>(____.class);

        // Merge the quantities into category sums
        rawData.forEach((raw, quantity) -> ____.____(categoryMap.get(raw), quantity, Integer::sum));

		System.out.println("Stock by category:");
        System.out.println(stockByCategory);
    }
}
編輯並執行程式碼