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

2 Answers
2

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.

The first sentence is a red herring. The Multisetinterface specifies a count method (which is the correct one to use). No need to use HashMultiset.count specifically.
–
Chris Jester-YoungOct 8 '11 at 8:49

Sure. But that doesn't change the fact that you should still just use the Multiset interface, rather than HashMultiset explicitly. (i.e., Multiset multiset = HashMultiset.create();, not HashMultiset multiset = HashMultiset.create();.) You would still operate in terms of the Multiset interface; only the factory method needs to care that it's a HashMultiset behind the scenes.
–
Chris Jester-YoungOct 8 '11 at 10:26

1

Yeah, this answer is so strangely explained I posted a new answer just to, you know, give the answer, directly.
–
Kevin BourrillionOct 8 '11 at 14:41

Thanks to all of you for the help! It works :))
–
seinecleOct 8 '11 at 15:12