如何在枚举映射中初始化计数?

How to initialize the count in a Map of enums?

问题:我希望生成的地图包含所有可用的 enums,如果在迭代列表中找不到,则使用 long = 0.

进行预初始化
List<Basket> basket;

Map<TypeOfGoods, Long> counts = basket.stream
      .collect(Collectors.groupingBy(Basket::getGoodsType, Collectors.counting()));

enum TypeOfGoods {
    FRUITS, TOYS;
}

在此示例中,地图将仅包含实际在篮子中找到的类型,但缺少任何其他枚举。我怎样才能包括这些?

尝试:

Map<TypeOfGoods, Long> counts = Arrays.stream(TypeOfGoods.values())
                        .collect(Collectors.toMap(identity(), x -> 0L));
counts.putAll(basket.stream
  .collect(Collectors.groupingBy(Basket::getGoodsType, Collectors.counting()));

另一种选择是使用 putIfAbsent:

Map<TypeOfGoods, Long> counts = basket.stream()
                .collect(groupingBy(Basket::getGoodsType, counting()));

Arrays.asList(TypeOfGoods.values()).forEach(e -> counts.putIfAbsent(e, 0L));