[英]Iterate an ArrayList to count by object attribute
我有一个已经初始化的产品的ArrayList
。 Product
构造函数为:
public Product(String number, String type, double rentalDeposit, double rentalPrice, double lateFee, double buyPrice, int maxDuration)
type
由枚举确定:
protected enum productType {Basket, BabySeat, Helmet, Headlight, Bell};
我通过在type
使用toString
为枚举方法。 我需要遍历我拥有的ArrayList<Product>
(由shop.getInventory()
),并计算每种type
数量,即, Basket
, BabySeat
, Helmet
等type
BabySeat
。
Product
类具有一个返回字符串的getType()
方法。
for (Product.productType product : Product.productType.values()) {
int occurences = Collections.frequency(shop.getInventory(), product.toString());
}
我已经尝试过使用Collections.frequency
,但是它一直返回0
,我不确定为什么。
还有另一种方法可以迭代并查找此数量而无需使用大量的if
语句吗?
shop.getInventory()
我假设其类型为Collection<Product>
。 您可以定义product,以便.equals(Product)
将检查Product的内部类型是否相等,或更简单地说,是shop.getInventory().stream().filter(item -> product.toString().equals(item.getType())).count()
。 (将item.getType()
替换item.getType()
您从Product中提取类型字段,例如item.type
等)。
对列表中符合某种条件的项目进行计数的一种简单方法是使用Collectors.groupingBy
和Collectors.counting
。 类似于以下内容:
Map<ProductType,Long> counts = products.stream()
.collect(groupingBy(Product::getType, counting()));
如果您不熟悉流,则此语句可以理解为“将列表转换为产品流,按产品类型对产品进行分组,然后对每个组进行计数,从而创建从类型到计数的映射。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.