David Marciel
David Marciel

Reputation: 939

Set counting items

I wonder if there are any java collection counting occurences in a set.

Since it just stores the references once and gets the number of times it was added it saves space but allows you to know the number of times it was added. It also saves space in case you need to know if there are available items or not.

For example:

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

I've been looking for it but I don't find a collection like this, could you tell me the best way to do it?

Upvotes: 2

Views: 498

Answers (3)

Donald Raab
Donald Raab

Reputation: 6706

You can use the Bag type from Eclipse Collections:

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

Note: I am a committer for Eclipse Collections.

Upvotes: 1

Bedla
Bedla

Reputation: 4919

You can use MultiSet from Apache Commons Collections.

Defines a collection that counts the number of times an object appears in the collection. Suppose you have a MultiSet that contains {a, a, b, c}. Calling getCount(Object) on a would return 2, while calling uniqueSet() would return {a, b, c}.

See this example:

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"));
    }
}

Upvotes: 3

Ousmane D.
Ousmane D.

Reputation: 56453

A Set doesn't allow duplicates. Instead look into using a Map<String, Integer> or a List<String> and then use Collections.frequency to get the count.

Upvotes: 4

Related Questions