java - 流API : create empty map with keys from enum

标签 java dictionary enums java-8

我有以下枚举:

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

我想使用 enum 中的键创建 map 和空值。我按照this answer尝试过以下代码:

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

但我得到 NullPointerException这里。我究竟做错了什么?

最佳答案

我很确定 EnumMap更适合您的需求。

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

对于枚举值,EnumMap 比 HashMap 更高效。缺省情况下,不存在任何映射关系。根据您的用例,这可能没问题(map.get(RED_MEAT) 返回 null,这似乎是您想要的),但如果您想执行 containsKey() 检查或循环条目,那么您必须显式地将映射设置为 null:

Arrays.stream(ProductType.values()).forEach(v-> diet.put(v, null));

关于java - 流API : create empty map with keys from enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40974700/

相关文章:

java - 我可以使用 Protobuf-net 对已用 Java 序列化的数据进行反序列化吗?

java - 为什么我的 JSP scriptlet 无法从 pageContext 检索 int 并将其转换为本地作用域的原始变量?

java - java的console.log()是什么?

java - 如果我增加内存堆是否会增加 GC 时间

c# - Android Java 到 C# URL

python - 将具有多个 if else 语句的函数转换为字典

c++ - 当两个 std::map 对象相同时

python - 将数据附加到python字典

c# - Enum ToString 显示为数字

swift - 如何将计算值转换为枚举初始化的文字