设置计数项目

时间:2018-04-29 12:35:27

标签: java collections set

我想知道是否有任何java集合计算集合中的出现次数。

由于它只存储一次引用并获得它的添加次数,因此可以节省空间,但可以让您知道它的添加次数。 它还可以节省空间,以防您需要知道是否有可用的物品。

例如:

Set<Object> counterSet = new Set<Object>();

counterSet.add("Hello");
counterSet.add("world");
counterSet.add("Hello");

counterSet.numberOfInstances("Hello"); //returns 2
counterSet.numberOfInstances("world"); //returns 1

我一直在找它,但我找不到这样的收藏品,你能告诉我最好的方法吗?

3 个答案:

答案 0 :(得分:4)

Set不允许重复。相反,请考虑使用Map<String, Integer>List<String>,然后使用Collections.frequency来获取计数。

答案 1 :(得分:3)

您可以使用MultiSet中的Apache Commons Collections

  

定义一个集合,该集合计算对象在集合中出现的次数。   假设您有一个包含{a,a,b,c}的MultiSet。在a上调用getCount(Object)将返回2,而调用uniqueSet()将返回{a,b,c}。

见这个例子:

public class MultiSetTest {
    @Test
    public void testMultiSet(){
        MultiSet<String> counterSet = new HashMultiSet<>();
        counterSet.add("Hello");
        counterSet.add("world");
        counterSet.add("Hello");

        Assert.assertEquals(2, counterSet.getCount("Hello"));
        Assert.assertEquals(1, counterSet.getCount("world"));
        Assert.assertEquals(0, counterSet.getCount("somethingMissing"));
    }
}

答案 2 :(得分:1)

您可以使用Bag中的Eclipse Collections类型:

Bag<String> bag = Bags.mutable.with("Hello", "world", "Hello");
Assert.assertEquals(2, bag.occurrencesOf("Hello"));
Assert.assertEquals(1, bag.occurrencesOf("world"));

注意:我是Eclipse Collections的提交者。