ComeçarComece de graça

Grouping by standardized categories

Now that you have standardized the categories of your electronics inventory, you would like to compute the quantity of each category. Merge the quantities into category sums.

Este exercício faz parte do curso

Cleaning Data in Java

Ver curso

Instruções do exercício

  • Define an enum map to store the quantity of each ProductCategory in stockByCategory.
  • Merge the quantities into category sums in stockByCategory.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

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", 10,
                "home appliances", 20,
                "HomeAppliances", 30,
                "Electronics", 10,
                "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);
    }
}
Editar e executar o código