Count the occurrences of items in ArrayList

后端 未结 6 831
长发绾君心
长发绾君心 2020-12-19 13:18

I have a java.util.ArrayList and an Item object.

Now, I want to obtain the number of times the Item is stored in t

6条回答
  •  长情又很酷
    2020-12-19 13:45

    I could be wrong, but it seems to me like the data structure you actually want might be a Multiset (from google-collections/guava) rather than a List. It allows multiples, unlike Set, but doesn't actually care about the order. Given that, it has a int count(Object element) method that does exactly what you want. And since it isn't a list and has implementations backed by a HashMap, getting the count is considerably more efficient.

提交回复
热议问题