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?

0

1 Answer 1

5

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.