Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the number of instances of an element in a guava multiset without iterating

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

like image 380
seinecle Avatar asked Aug 11 '26 14:08

seinecle


2 Answers

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

like image 84
Kevin Bourrillion Avatar answered Aug 13 '26 04:08

Kevin Bourrillion


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.

like image 32
卢声远 Shengyuan Lu Avatar answered Aug 13 '26 03:08

卢声远 Shengyuan Lu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!