LoslegenKostenlos loslegen

Building a category mapping

You are managing inventory for your electronics store, and you need to standardize the electronics categories in your inventory. Create a category mapping to help keep track of the products in your store.

The necessary packages such as EnumMap, and HashMap have been imported for you.

Diese Übung ist Teil des Kurses

Cleaning Data in Java

Kurs anzeigen

Anleitung zur Übung

  • Create an enum called ProductCategory.
  • Look up an unknown category called "Mystery category".
  • Create an unmodifiable map using categoryMap.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

public class ElectronicsCategoryExample {
	// Create an enum called ProductCategory
    public ____ ____ {
        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);
        
        System.out.println("Electronics category:");
        System.out.println(categoryMap.get("Electronics"));
        
        // Look up an unknown category
        ProductCategory unknownCategory = ____.____(
    			"Mystery category", ProductCategory.UNCATEGORIZED);
                
        System.out.println("\nMystery category:");
        System.out.println(unknownCategory);
        
        // Create an unmodifiable map
        Map immutableMap = ____.____(categoryMap);
        
        System.out.println("\nAttempting to modify immutable map:");
        try {
            immutableMap.put("new", ProductCategory.ELECTRONICS);
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify immutable map");
        }
    }
}
Code bearbeiten und ausführen