简体   繁体   English

迭代ArrayList以按对象属性计数

[英]Iterate an ArrayList to count by object attribute

I have an ArrayList of products already initialized. 我有一个已经初始化的产品的ArrayList The Product constructor is: Product构造函数为:

public Product(String number, String type, double rentalDeposit, double rentalPrice, double lateFee, double buyPrice, int maxDuration)

The type is determined by an enumeration: type由枚举确定:

protected enum productType {Basket, BabySeat, Helmet, Headlight, Bell};

I pass in the type using the toString method for the enumeration. 我通过在type使用toString为枚举方法。 I need to iterate through the ArrayList<Product> (given by shop.getInventory() ) that I have and count how many of each type there are, ie how many are of type Basket , BabySeat , Helmet , etc. 我需要遍历我拥有的ArrayList<Product> (由shop.getInventory() ),并计算每种type数量,即, BasketBabySeatHelmettype BabySeat

The Product class has a getType() method that returns a string. Product类具有一个返回字符串的getType()方法。

for (Product.productType product : Product.productType.values()) {
    int occurences = Collections.frequency(shop.getInventory(), product.toString());
}

I have tried using Collections.frequency , but it keeps returning 0 and I'm not sure why. 我已经尝试过使用Collections.frequency ,但是它一直返回0 ,我不确定为什么。

Is there another way to iterate through and find this amount without using a ton of if statements? 还有另一种方法可以迭代并查找此数量而无需使用大量的if语句吗?

shop.getInventory() I'll assume has the type Collection<Product> . shop.getInventory()我假设其类型为Collection<Product> You can either define product such that .equals(Product) will check equality against the Product's internal type, or even more simply, shop.getInventory().stream().filter(item -> product.toString().equals(item.getType())).count() . 您可以定义product,以便.equals(Product)将检查Product的内部类型是否相等,或更简单地说,是shop.getInventory().stream().filter(item -> product.toString().equals(item.getType())).count() (replace item.getType() with however you extract the type field from Product, like maybe item.type etc). (将item.getType()替换item.getType()您从Product中提取类型字段,例如item.type等)。

A simple method of counting items in a list that correspond to some condition is to use Collectors.groupingBy and Collectors.counting . 对列表中符合某种条件的项目进行计数的一种简单方法是使用Collectors.groupingByCollectors.counting Something like the following: 类似于以下内容:

Map<ProductType,Long> counts = products.stream()
    .collect(groupingBy(Product::getType, counting()));

If you're not familiar with streams, this statement can be read as 'turn the list into a stream of products, group the products by product type then count each of those groups creating a map from the type to the count.' 如果您不熟悉流,则此语句可以理解为“将列表转换为产品流,按产品类型对产品进行分组,然后对每个组进行计数,从而创建从类型到计数的映射。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM