Home > OS >  Kotlin list.map() how to avoid ConcurrentModificationException
Kotlin list.map() how to avoid ConcurrentModificationException

Time:10-02

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 ?

CodePudding user response:

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

CodePudding user response:

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

with(arrDeltaBrainWaves.iterator()) {
 forEach {
    
 }
}
  • Related