0

I have following enum:

public enum ProductType {
    RED_MEAT, POULTRY, FISH, EGGS, NUTS, DAIRY, CERIALS_AND_GRAINS, FRUIT, VEGETABLES, OIL_AND_SUGARS
}

I would like to create map with keys from the enum and null values. I tried according to this answer following code:

Map<ProductType, DietFrequency> diet = Arrays.stream(ProductType.values())
        .collect(Collectors.toMap(productType -> productType, value -> null));

But I am getting NullPointerException here. What am I doing wrong?

Community
  • 1
  • 1
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192

1 Answers1

4

I am pretty sure an EnumMap is more suited to your needs.

Map<ProductType, DietFrequency> diet = new EnumMap<>(ProductType.class);

An EnumMap is much more efficient than a HashMap, for enum values. By default, no mappings exist. Depending on your use case, that may be fine (map.get(RED_MEAT) returns null, which seems to be what you want), but if you want to do a containsKey() check or loop over entries, then you'll have to explicitly set the mappings to null:

Arrays.stream(ProductType.values()).forEach(v-> diet.put(v, null));
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588