PositiveGuy
PositiveGuy

Reputation: 20212

Get count of items in ArrayList based on property on type

I'm trying to get a count of how many Items are of itemTypeId 1

Item

public class Item {
  private int itemTypeId;

  public int getItemTypeId() {
    return this.itemTypeId;
  }
}

So for example lets say we have 4 instances of the above. 2 of them have an itemTypeId of 1. Then and we add them to an ArrayList:

ArrayList<Item> items = new Array<>();
items.push(item1);
items.push(item2);
items.push(item3);
items.push(item4);

I need to get the count of how many items have an itemTypeId of 1:

Integer quantityOfTypeOne = ???

This did not work, it says equals() is not a method it recognizes

Integer quantityOfTypeOne = items.stream().filter(item -> item.getItemTypeId().equals(1).collect(Collectors.toList()));

and I tried == which I think is not a good way to compare integers anyway:

Integer quantityOfTypeOne = items.stream().filter(item -> item.getItemTypeId() == 1).collect(Collectors.toList()));

Upvotes: 0

Views: 737

Answers (3)

PositiveGuy
PositiveGuy

Reputation: 20212

I got it working even simpler with:

items.stream().filter(item -> item.getItemTypeId() == 1).count()

Upvotes: 0

You said you only want the count, so a simple reducing stream is idiomatic:

items.stream()
  .mapToInt(Item::getItemTypeId)
  .filter(id -> id == 1)
  .count()

Upvotes: 1

Shashank Kadne
Shashank Kadne

Reputation: 8101

Please use == for comparing primitive integers.

int quantityOfTypeOne  = items.stream().filter(item -> item.getItemTypeId()==1).collect(Collectors.toList()).size();

Learn more about Operators in Java.

Upvotes: 1

Related Questions