Java在HashSet中找到最常见的值
好的,这是一个基本问题,但我想知道解决这个问题的最佳方法是什么...
我有一个要向其中添加对象的 HashSet,.add() 方法只会添加一个对象(如果尚未添加)展示。但我想做的是添加所有对象,然后最后得到以下结果..
-唯一(不同)对象的数量
-物体的平均频率
有人能指出我正确的方向吗?
提前致谢
Ok bit of a basic question here but I wanted to know what the best way to go about this...
I have a HashSet that I am adding objects to, the .add() method will only add an object if it is not already present. But what I want to do is add ALL objects, then at the end get the following results..
-Number of unique (distinct) objects
-The average frequency of objects
Could someone point me in the right direction?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用哈希映射。使用条目作为键,并将它们映射到整数以保留计数。
编辑:您可能想要包装 HashMap,以确保每次添加或删除对象时,计数器都会被适当修改。
让您开始:
Use a HashMap. Use the entries as key, and map them to an Integer to keep the count.
EDIT: you may want to wrap the HashMap, to make sure that every time an object is added or removed, the counter is modified appropriately.
To get you started:
HashSet 并不适合跟踪个人计数,但 HashMap 几乎是完美的。
运行时,这个独立的代码片段输出
HashSet isn't really suited for keeping track of individual counts but HashMap is nearly perfect.
When run, this standalone snippet outputs
不同对象的数量将只是之后哈希集的大小。
根据“平均频率”的含义,您可能可以使用
source.size() / set.size()
...(可能将其中一个操作数转换为double 强制浮点运算(如果需要)。如果您可以通过一些示例详细说明您的需求,我们也许可以提供更多帮助。
The number of distinct objects will just be the size of the hash set afterwards.
Depending on what you mean by "average frequency" you may be okay with
source.size() / set.size()
... (possibly casting one of the operands todouble
to force floating point arithmetic if you want). If you can elaborate on what you need with some examples, we may be able to help more.Guava HashMultiset 是一个方便的工具选择。例如:
Guava HashMultiset is a convenient choice. For instance:
您可以只使用 (Hash)Map,而不是将每个不同对象的计数保留为映射中的值,或者您可以继续使用集合,但在某处计算所有要添加的调用。
插入的对象总数要么是您计算的数量,要么是映射中所有值的总和(迭代 EntrySet)。不同对象的数量始终是地图/集合的 size() 和平均值。频率显然是商。
You can either just use a (Hash)Map instead an keep the count for each distinct object as value in the map, or you can keep using a set but somewhere count all calls to add.
The total number of objects inserted is either what you counted or the sum over all values in the map (iterate over the EntrySet). The number of distinct objects is always size() of your map / set and the avg. frequency obviously is the quotient.
对于这种情况,我使用我自己的 Map 接口实现:
和实现:
行为如下:
您可以通过获取列表的大小轻松地按键(频率)计算元素的数量。
您可以获取列表的第一个或最后一个元素,以便获取具有指定键的第一个或最后一个添加值。
For such case i use my own implementation of Map interface:
And implementation:
The behavior is next:
You can easily count number of elements by key (frequencies) by getting size of list.
You can get either first or last element of list in order to get first or last added value with specified key.