การจัดกลุ่มตามหมวดหมู่ที่มาตรฐานแล้ว
หลังจากที่ได้มาตรฐานหมวดหมู่ของสินค้าอิเล็กทรอนิกส์แล้ว ขั้นตอนต่อไปคือการคำนวณจำนวนสินค้าในแต่ละหมวดหมู่ โดยการรวมจำนวนสินค้าเข้าด้วยกันเป็นผลรวมของแต่ละหมวดหมู่
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำความสะอาดข้อมูลใน Java
คำแนะนำการฝึกหัด
- กำหนด
enummap สำหรับเก็บจำนวนสินค้าของแต่ละProductCategoryไว้ในstockByCategory - รวมจำนวนสินค้าเป็นผลรวมของแต่ละหมวดหมู่ใน
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);
}
}