Question

I have a multiset in guava and I would like to retrieve the number of instances of a given element without iterating over this multiset (I don't want to iterate because I assume that iterating takes quite some time, as it looks through all the collection).

To do that, I was thinking first to use the entryset() method of multiset, to obtain a set with single instances and their corresponding count. Then, transform this set into a hashmap (where keys are the elements of my set, and values are their instance count). Because then I can use the methods of hashmap to directly retrieve a value from its key - done! But this makes sense only if I can transform the set into the hashmap in a quick way (without iterating trhough all elements): is it possible?

(as I said I expect this question to be flawed on multiple counts, I'd be happy if you could shed light on the conceptual mistakes I probably make here. Thx!)

Was it helpful?

Solution

You may know in Guava Multiset is an interface, not a class.

If you just want to know the repeated number of an element, call Multiset.count(Object element).

Please forget my following statement:

Then if you are using a popular implementation HashMultiset, there is already a HashMap<E, AtomicInteger> working under the scene. That is, when the HashMultiset iterates, also a HashMap iterates. No need to transform into another HashMap.

OTHER TIPS

Simply invoke count(element) on your multiset -- voila!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top