0
Multiset<String> ngrams = HashMultiset.create();  
//added strings to the multiset...

    for (Entry<String> entry : ngrams.entrySet()) {
       if (entry.getCount() > 3) {
          ngrams.setCount(terms, 3);
       }
    }

Throws a ConcurrentModificationException

How can I use setCount() without throwing this exception? Could some Java 8 code be useful here?

dryairship
  • 6,022
  • 4
  • 28
  • 54
seinecle
  • 10,118
  • 14
  • 61
  • 120

1 Answers1

1

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

Community
  • 1
  • 1
mfulton26
  • 29,956
  • 6
  • 64
  • 88