setCount(E, int)
will only throw a ConcurrentModificationException
if the element count in the HashMultiset
is zero.
i.e. If ngrams
already contains terms
then changing terms
count will not throw a ConcurrentModificationException
.
e.g. You can add terms
using a special count value (e.g. Integer.MAX_VALUE
) before iterating and then remove it after iterating if it wasn't changed:
Multiset<String> ngrams = HashMultiset.create();
//added strings to the multiset...
ngrams.setCount(terms, Integer.MAX_VALUE);
for (Multiset.Entry<String> entry : ngrams.entrySet()) {
if (entry.getElement().equals(terms)) {
continue;
}
if (entry.getCount() > 3) {
ngrams.setCount(terms, 3);
}
}
if (ngrams.count(terms) == Integer.MAX_VALUE) {
ngrams.setCount(terms, 0);
}
If your situation is more complicated then you'll probably be better off creating a new Multiset<String>
as Andy Turner suggests instead of modifying and iterating concurrently. (Or some other solution that doesn't involve concurrent iteration and modification, etc.)