0

I have an ArrayList of products already initialized. The Product constructor is:

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

The type is determined by an enumeration:

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

I pass in the type using the toString method for the enumeration. I need to iterate through the ArrayList<Product> (given by shop.getInventory()) that I have and count how many of each type there are, i.e. how many are of type Basket, BabySeat, Helmet, etc.

The Product class has a getType() method that returns a string.

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.

Is there another way to iterate through and find this amount without using a ton of if statements?

aaron
  • 39,695
  • 6
  • 46
  • 102
Cass
  • 1
  • 1
  • Try replacing: `shop.getInventory()` with: `shop.getInventory().stream().map(product -> `product.productType`).collect(Collectors.toList())` (and get rid of the for-loop - it's not needed). – Nir Alfasi Dec 01 '17 at 02:35

2 Answers2

0

shop.getInventory() I'll assume has the type 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(). (replace item.getType() with however you extract the type field from Product, like maybe item.type etc).

Rahul Manne
  • 1,229
  • 10
  • 20
0

A simple method of counting items in a list that correspond to some condition is to use Collectors.groupingBy and Collectors.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.'

sprinter
  • 27,148
  • 6
  • 47
  • 78