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.
This exercise is part of the course
Cleaning Data in Java
Exercise instructions
- Create an
enum
calledProductCategory
. - Look up an unknown category called
"Mystery category"
. - Create an unmodifiable map using
categoryMap
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
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");
}
}
}