Kotlin list.map() how to avoid ConcurrentModificationException

2.9k Views Asked by At

I have problem with ConcurrentModificationException. Here's my part of the code :

    var deltaSum = 0
    arrDeltaBrainWaves.map {
         value -> deltaSum += value
   }

To be clear - I know why this error appears :) The problem is - I have no idea what's the solution ? Do I really need to create new temp list and put values there ? It just doesnt make sense :) Any better options, please ?

EDIT:

I changed the code to below :

var deltaSum = 0
                                with(arrDeltaBrainWaves.iterator()) {
                                    forEach {
                                        deltaSum += it
                                    }
                                }
                                avgDelta = deltaSum / arrDeltaBrainWaves.size

But problem still exists.

3

There are 3 best solutions below

2
On

you need to use the Iterators

example:

val myCollection = mutableListOf(1,2,3,4)
val iterator = myCollection.iterator()
while(iterator.hasNext()){
    val item = iterator.next()
    //do something
}

this will avoid ConcurrentModificationExceptions

5
On

The ConcurrentModificationException can be avoided by using iterators. Here is kotlin way to do so:

with(arrDeltaBrainWaves.iterator()) {
 forEach {
    
 }
}
0
On

I solved the ConcurrentModificationException by using MutableListIterator in Kotlin

OLD CODE :

registeredListeners.forEach { it.notifyObservers() }

(In my case notifyObservers() is removing object from the registeredListeners list which is the cause of the exception)

NEW CODE :

val iterator = registeredListeners.toMutableList().listIterator()
while (iterator.hasNext()) {
    iterator.next().notifyObservers()
}

Hope it helps :)