计数项目在ArrayList中出现 [英] Count the occurrences of items in ArrayList

查看:152
本文介绍了计数项目在ArrayList中出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的java.util.ArrayList<项目方式> 项目对象

现在,我想获得的次数项目存储在ArrayList中。

我知道我能做到 arrayList.contains()检查,但它是否包含一个或多个物品返回true,不论秒。

Q1。我如何才能找到的项目被存储在列表的时间有多少?

Q2。此外,如果列表中包含多个项目,那我怎么才能确定其他项目的索引,因为 arrayList.indexOf(项目)返回每次只有第一项的索引?


解决方案

您可以使用收藏类:

 公共静态INT频率(收集&LT​​;> C,对象o)


  

返回指定集合中的元素等于所述指定的对象的数量。更正式地说,返回集合中的元素e的数量满足(o == NULLË== NULL:o.equals(e)项)。


如果你需要计算一个长长的清单occurencies很多次,我建议你使用一个的HashMap 存储柜和更新它们在插入新项目到列表。这将避免计算任何形式的专柜..但你当然不会有指数。

 的HashMap<项目,整数GT;计数器=新的HashMap<项目,整数GT;(5000);
ArrayList的<项目>项目=新的ArrayList<项目>(5000);无效插入(项目墩)
{
   如果(counters.contains(墩))
     counters.put(墩,counters.get(墩)+1);
   其他
     counters.put(墩,1);   items.add(墩);
 }

最后一个提示:您可以使用其他集合框架(如阿帕奇集合)并使用数据结构被描述为


  

定义计数的对象出现在集合中的次数的集合。


所以,你需要的东西。

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 Items.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆