计算 ArrayList 中项目的出现次数 [英] Count the occurrences of items in ArrayList
问题描述
我有一个 java.util.ArrayList
和一个 Item
对象.
现在,我想获取Item
在arraylist 中存储的次数.
我知道我可以做 arrayList.contains()
检查,但它返回 true,不管它是否包含一个或多个 Item
.
第一季度.如何查找 Item 在列表中存储的次数?
第 2 季度.另外,如果列表包含多个项目,那么我如何确定其他项目的索引,因为 arrayList.indexOf(item)
每次只返回第一个项目的索引?
您可以使用 Collections
类:
public static int frequency(Collection>c, Object o)
<块引用>
返回指定集合中与指定对象相等的元素数.更正式地,返回集合中元素 e 的数量,使得 (o == null ? e == null : o.equals(e)).
如果您需要多次计算长列表的出现次数,我建议您使用 HashMap
来存储计数器并在向列表中插入新项目时更新它们.这将避免计算任何类型的计数器......但当然你不会有索引.
HashMap- counters = new HashMap
- (5000);ArrayList<项目>items = new ArrayList
- (5000);无效插入(项目 newEl){如果(计数器.包含(newEl))counters.put(newEl, counters.get(newEl)+1);别的counters.put(newEl, 1);items.add(newEl);}
最后提示:您可以使用其他集合框架(例如 Apache Collections)并使用 Bag
数据结构被描述为
定义一个集合,用于计算对象在集合中出现的次数.
正是您所需要的..
I have a java.util.ArrayList<Item>
and an Item
object.
Now, I want to obtain the number of times the Item
is stored in the arraylist.
I know that I can do arrayList.contains()
check but it returns true, irrespective of whether it contains one or more Item
s.
Q1. How can I find the number of time the Item is stored in the list?
Q2. Also, If the list contains more than one Item, then how can I determine the index of other Items because arrayList.indexOf(item)
returns the index of only first Item every time?
You can use Collections
class:
public static int frequency(Collection<?> c, Object o)
Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).
If you need to count occurencies of a long list many times I suggest you to use an HashMap
to store the counters and update them while you insert new items to the list. This would avoid calculating any kind of counters.. but of course you won't have indices.
HashMap<Item, Integer> counters = new HashMap<Item, Integer>(5000);
ArrayList<Item> items = new ArrayList<Item>(5000);
void insert(Item newEl)
{
if (counters.contains(newEl))
counters.put(newEl, counters.get(newEl)+1);
else
counters.put(newEl, 1);
items.add(newEl);
}
A final hint: you can use other collections framework (like Apache Collections) and use a Bag
datastructure that is described as
Defines a collection that counts the number of times an object appears in the collection.
So exactly what you need..
这篇关于计算 ArrayList 中项目的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!