67

I have a list of accounts, and when i make the long click, I want to remove the item from the arraylist. I'm trying to remove it from a alertdialog, but i'm getting the ConcurrentModificationException. This is where is crashing:

listAccounts.forEachIndexed { index, account ->
    if (idParamether == account.id) {
        listAccounts.remove(account)
    }
}
julianstark999
  • 3,450
  • 1
  • 27
  • 41
zasaz
  • 2,404
  • 2
  • 15
  • 27
  • 1
    Possible duplicate of [Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – leonardkraemer Apr 25 '18 at 22:20
  • I know the duplicate is Java, but in essence it's the same. But you can handle it in a nicer way. – leonardkraemer Apr 25 '18 at 22:20

11 Answers11

67

That's a common problem with the JVM, if you want to remove an item from a collection while iterating through it, you need to use the Iterators

exemple:

val myCollection = mutableListOf(1,2,3,4)
val iterator = myCollection.iterator()
while(iterator.hasNext()){
    val item = iterator.next()
    if(item == 3){
        iterator.remove()
    }
}

this will avoid ConcurrentModificationExceptions

I hope this answered your question, have a good day

Edit: you can find another explanation here, even if it is Java code the problem is the same
Edit n°2 the anwser of leonardkraemer show you a more kotlin-friendly way to do so

SeekDaSky
  • 1,037
  • 10
  • 10
40

In Kotlin you can use removeIf{ predicate }. Which is a shorthand to using the Iterator. Full statement:

listAccounts.removeIf{ it == account.id }

for the explanation see Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

Update: Kotlin-stdlib introduced removeAll { predicate } which, as Aguragorn pointed out in his answer, does the same and can be used if removeIf is not present on your runtime environment (i.e. Java 1.6 or Android pre API level 24).

leonardkraemer
  • 6,573
  • 1
  • 31
  • 54
  • 11
    Not to forget that this Call requires API level 24 – Vikas Patidar Apr 27 '18 at 13:35
  • 1
    @VikasPatidar Yes API level 24 is required for Android, that introduces the Java 8 features necessary. – leonardkraemer Apr 27 '18 at 13:42
  • hey @leonardkraemer how to use this with adding item to list i have this error when adding can i use this : list.listIterator().add(item) – Ayoub Benzahia Dec 30 '20 at 20:53
  • It's possible to use the method pre-API 24 with the [core library desugaring](https://developer.android.com/studio/write/java8-support) feature introduced a while ago. – bompf May 12 '21 at 13:03
19
with(listAccounts.iterator()) {
    forEach {
        if (it.id == someObj.id) {
            // do some stuff with it
            oldSubscription = it
            remove()
        }
    }
}

Same solution as SeekDaSky but more Kotlin'y

Tomas
  • 4,652
  • 6
  • 31
  • 37
Ryan
  • 227
  • 2
  • 3
16

It is actually removeAll { predicate } that kotlin stdlib introduced. So your code should look like this:

listAccounts.removeAll { it.id == idParamether }

see: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/remove-all.html

Note: when coding in kotlin I prefer sticking to kotlin APIs, it avoids problems like "Call requires API level 24"

Aguragorn
  • 585
  • 6
  • 14
8

Try to use ConcurrentLinkedQueue instead of list to avoid this exception. As mentioned in ConcurrentLinkedQueue.Java, it orders elements FIFO (first-in-first-out).So it will avoid any problem with modifying a list while iterating it.
For exemple :

val list = ConcurrentLinkedQueue<String>()
list.add("toto")
list.add("tata")
list.add("titi")
list.forEachIndexed { index, it ->
    if (index % 2 == 0) {
        list.remove("tata")
        System.out.println(it)
    }
}

the out put is :

toto
titi

julianstark999
  • 3,450
  • 1
  • 27
  • 41
6

I also had this problem and I solved it simply by cloning the starting list, so I go through that and add or remove elements in the original one.

This code gave me the exception:

 for(account in listAccounts){
    ....
    listAccounts.add(anotherAccount)
    ....

}

So just replace it with this:

val listAccountCloned = listAccounts.toMutableList()
 for(account in listAccountCloned){
    ....
    listAccounts.add(anotherAccount)
    ....

}

Adamo Branz
  • 164
  • 2
  • 7
  • As Slion said before, this solution could be useful with small lists, but maybe could be a inefficient solution for lists with considerable size. Anyways, good solution! thanks! – zasaz Jul 21 '21 at 12:23
2

You can make a copy of your list before iterating through it. It's a valid solution for small lists. That's what they are typically doing on Android before iterating through listeners for instance.

Slion
  • 2,558
  • 2
  • 23
  • 27
1

I'd like to supplement Ryan's answer. If you'd like to add to your list during iteration, not just remove, you'd need to call .listIterator() on your collection instead of .iterator(). Then you'll have the add method too thanks to this interface. Complete code:

with(listAccounts.listIterator()) {
    forEach {
        if (it.id == someObj.id) {
            // do some stuff with it
            oldSubscription = it
            remove()
            add(obj)
        }
    }
}

Note: I know the OP just wanted to remove, but the title is more general and this is also the question you find if you search for adding in this situation too.

Tamás Sajti
  • 53
  • 1
  • 7
1

the simplest way to solve this issue would be just adding "break" after the remove

for (i in accounts) {
                    if (nick == i.nick) {
                        print("Enter PIN: ")
                        var pin = scan.nextInt()
                        if (pin == i.pin) {
                            accounts.remove(i)
                            println("Account has been deleted successfully!")
                            break
                        }
                    }
                }
0

solution as kotlin extension:

inline fun <T> List<T>.forEachIterable(block: (T) -> Unit) {
   with(iterator()) {
      while (hasNext()) {
         block(next())
      }
  }
}
Marek Kondracki
  • 1,372
  • 2
  • 8
  • 13
0

Iterators are not always helpful when another thread also modifies the collection. I had tried many ways but then I realized traversing manually the collection is much safer (backward for remove):

for (i in listAccounts.size-1 downTo 0) {
    myList.getOrNull(i)?.apply {
       if (id == idParameter)
          listAccounts.remove(this)
    }
}
Saeed Ir
  • 1,974
  • 2
  • 20
  • 22